aoptx86.pas 559 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099
  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,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3
  33. );
  34. TX86AsmOptimizer = class(TAsmOptimizer)
  35. { some optimizations are very expensive to check, so the
  36. pre opt pass can be used to set some flags, depending on the found
  37. instructions if it is worth to check a certain optimization }
  38. OptsToCheck : set of TOptsToCheck;
  39. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  40. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  41. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  42. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  43. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  44. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  45. potentially allowing further optimisation (although it might need to know if
  46. it crossed a conditional jump. }
  47. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  48. {
  49. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  50. the use of a register by allocs/dealloc, so it can ignore calls.
  51. In the following example, GetNextInstructionUsingReg will return the second movq,
  52. GetNextInstructionUsingRegTrackingUse won't.
  53. movq %rdi,%rax
  54. # Register rdi released
  55. # Register rdi allocated
  56. movq %rax,%rdi
  57. While in this example:
  58. movq %rdi,%rax
  59. call proc
  60. movq %rdi,%rax
  61. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  62. won't.
  63. }
  64. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  65. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  66. private
  67. function SkipSimpleInstructions(var hp1: tai): Boolean;
  68. protected
  69. class function IsMOVZXAcceptable: Boolean; static; inline;
  70. { Attempts to allocate a volatile integer register for use between p and hp,
  71. using AUsedRegs for the current register usage information. Returns NR_NO
  72. if no free register could be found }
  73. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  74. { Attempts to allocate a volatile MM register for use between p and hp,
  75. using AUsedRegs for the current register usage information. Returns NR_NO
  76. if no free register could be found }
  77. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  78. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  79. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  80. { checks whether reading the value in reg1 depends on the value of reg2. This
  81. is very similar to SuperRegisterEquals, except it takes into account that
  82. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  83. depend on the value in AH). }
  84. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  85. { Replaces all references to AOldReg in a memory reference to ANewReg }
  86. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  87. { Replaces all references to AOldReg in an operand to ANewReg }
  88. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  89. { Replaces all references to AOldReg in an instruction to ANewReg,
  90. except where the register is being written }
  91. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  93. or writes to a global symbol }
  94. class function IsRefSafe(const ref: PReference): Boolean; static;
  95. { Returns true if the given MOV instruction can be safely converted to CMOV }
  96. class function CanBeCMOV(p : tai) : boolean; static;
  97. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  98. conversion was successful }
  99. function ConvertLEA(const p : taicpu): Boolean;
  100. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  101. procedure DebugMsg(const s : string; p : tai);inline;
  102. class function IsExitCode(p : tai) : boolean; static;
  103. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  104. procedure RemoveLastDeallocForFuncRes(p : tai);
  105. function DoSubAddOpt(var p : tai) : Boolean;
  106. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  107. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  108. function PrePeepholeOptSxx(var p : tai) : boolean;
  109. function PrePeepholeOptIMUL(var p : tai) : boolean;
  110. function PrePeepholeOptAND(var p : tai) : boolean;
  111. function OptPass1Test(var p: tai): boolean;
  112. function OptPass1Add(var p: tai): boolean;
  113. function OptPass1AND(var p : tai) : boolean;
  114. function OptPass1_V_MOVAP(var p : tai) : boolean;
  115. function OptPass1VOP(var p : tai) : boolean;
  116. function OptPass1MOV(var p : tai) : boolean;
  117. function OptPass1Movx(var p : tai) : boolean;
  118. function OptPass1MOVXX(var p : tai) : boolean;
  119. function OptPass1OP(var p : tai) : boolean;
  120. function OptPass1LEA(var p : tai) : boolean;
  121. function OptPass1Sub(var p : tai) : boolean;
  122. function OptPass1SHLSAL(var p : tai) : boolean;
  123. function OptPass1FSTP(var p : tai) : boolean;
  124. function OptPass1FLD(var p : tai) : boolean;
  125. function OptPass1Cmp(var p : tai) : boolean;
  126. function OptPass1PXor(var p : tai) : boolean;
  127. function OptPass1VPXor(var p: tai): boolean;
  128. function OptPass1Imul(var p : tai) : boolean;
  129. function OptPass1Jcc(var p : tai) : boolean;
  130. function OptPass1SHXX(var p: tai): boolean;
  131. function OptPass1VMOVDQ(var p: tai): Boolean;
  132. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  133. function OptPass2Movx(var p : tai): Boolean;
  134. function OptPass2MOV(var p : tai) : boolean;
  135. function OptPass2Imul(var p : tai) : boolean;
  136. function OptPass2Jmp(var p : tai) : boolean;
  137. function OptPass2Jcc(var p : tai) : boolean;
  138. function OptPass2Lea(var p: tai): Boolean;
  139. function OptPass2SUB(var p: tai): Boolean;
  140. function OptPass2ADD(var p : tai): Boolean;
  141. function OptPass2SETcc(var p : tai) : boolean;
  142. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  143. function PostPeepholeOptMov(var p : tai) : Boolean;
  144. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  145. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  146. function PostPeepholeOptXor(var p : tai) : Boolean;
  147. {$endif x86_64}
  148. function PostPeepholeOptAnd(var p : tai) : boolean;
  149. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  150. function PostPeepholeOptCmp(var p : tai) : Boolean;
  151. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  152. function PostPeepholeOptCall(var p : tai) : Boolean;
  153. function PostPeepholeOptLea(var p : tai) : Boolean;
  154. function PostPeepholeOptPush(var p: tai): Boolean;
  155. function PostPeepholeOptShr(var p : tai) : boolean;
  156. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  157. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  158. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  159. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  160. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  161. { Processor-dependent reference optimisation }
  162. class procedure OptimizeRefs(var p: taicpu); static;
  163. end;
  164. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  165. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  166. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  167. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  168. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  169. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  170. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  171. {$if max_operands>2}
  172. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  173. {$endif max_operands>2}
  174. function RefsEqual(const r1, r2: treference): boolean;
  175. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  176. { returns true, if ref is a reference using only the registers passed as base and index
  177. and having an offset }
  178. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  179. implementation
  180. uses
  181. cutils,verbose,
  182. systems,
  183. globals,
  184. cpuinfo,
  185. procinfo,
  186. paramgr,
  187. aasmbase,
  188. aoptbase,aoptutils,
  189. symconst,symsym,
  190. cgx86,
  191. itcpugas;
  192. {$ifdef DEBUG_AOPTCPU}
  193. const
  194. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  195. {$else DEBUG_AOPTCPU}
  196. { Empty strings help the optimizer to remove string concatenations that won't
  197. ever appear to the user on release builds. [Kit] }
  198. const
  199. SPeepholeOptimization = '';
  200. {$endif DEBUG_AOPTCPU}
  201. LIST_STEP_SIZE = 4;
  202. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  203. begin
  204. result :=
  205. (instr.typ = ait_instruction) and
  206. (taicpu(instr).opcode = op) and
  207. ((opsize = []) or (taicpu(instr).opsize in opsize));
  208. end;
  209. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  210. begin
  211. result :=
  212. (instr.typ = ait_instruction) and
  213. ((taicpu(instr).opcode = op1) or
  214. (taicpu(instr).opcode = op2)
  215. ) and
  216. ((opsize = []) or (taicpu(instr).opsize in opsize));
  217. end;
  218. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  219. begin
  220. result :=
  221. (instr.typ = ait_instruction) and
  222. ((taicpu(instr).opcode = op1) or
  223. (taicpu(instr).opcode = op2) or
  224. (taicpu(instr).opcode = op3)
  225. ) and
  226. ((opsize = []) or (taicpu(instr).opsize in opsize));
  227. end;
  228. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  229. const opsize : topsizes) : boolean;
  230. var
  231. op : TAsmOp;
  232. begin
  233. result:=false;
  234. if (instr.typ <> ait_instruction) or
  235. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  236. exit;
  237. for op in ops do
  238. begin
  239. if taicpu(instr).opcode = op then
  240. begin
  241. result:=true;
  242. exit;
  243. end;
  244. end;
  245. end;
  246. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  247. begin
  248. result := (oper.typ = top_reg) and (oper.reg = reg);
  249. end;
  250. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  251. begin
  252. result := (oper.typ = top_const) and (oper.val = a);
  253. end;
  254. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  255. begin
  256. result := oper1.typ = oper2.typ;
  257. if result then
  258. case oper1.typ of
  259. top_const:
  260. Result:=oper1.val = oper2.val;
  261. top_reg:
  262. Result:=oper1.reg = oper2.reg;
  263. top_ref:
  264. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  265. else
  266. internalerror(2013102801);
  267. end
  268. end;
  269. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  270. begin
  271. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  272. if result then
  273. case oper1.typ of
  274. top_const:
  275. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  276. top_reg:
  277. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  278. top_ref:
  279. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  280. else
  281. internalerror(2020052401);
  282. end
  283. end;
  284. function RefsEqual(const r1, r2: treference): boolean;
  285. begin
  286. RefsEqual :=
  287. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  288. (r1.relsymbol = r2.relsymbol) and
  289. (r1.segment = r2.segment) and (r1.base = r2.base) and
  290. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  291. (r1.offset = r2.offset) and
  292. (r1.volatility + r2.volatility = []);
  293. end;
  294. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  295. begin
  296. Result:=(ref.offset=0) and
  297. (ref.scalefactor in [0,1]) and
  298. (ref.segment=NR_NO) and
  299. (ref.symbol=nil) and
  300. (ref.relsymbol=nil) and
  301. ((base=NR_INVALID) or
  302. (ref.base=base)) and
  303. ((index=NR_INVALID) or
  304. (ref.index=index)) and
  305. (ref.volatility=[]);
  306. end;
  307. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  308. begin
  309. Result:=(ref.scalefactor in [0,1]) and
  310. (ref.segment=NR_NO) and
  311. (ref.symbol=nil) and
  312. (ref.relsymbol=nil) and
  313. ((base=NR_INVALID) or
  314. (ref.base=base)) and
  315. ((index=NR_INVALID) or
  316. (ref.index=index)) and
  317. (ref.volatility=[]);
  318. end;
  319. function InstrReadsFlags(p: tai): boolean;
  320. begin
  321. InstrReadsFlags := true;
  322. case p.typ of
  323. ait_instruction:
  324. if InsProp[taicpu(p).opcode].Ch*
  325. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  326. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  327. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  328. exit;
  329. ait_label:
  330. exit;
  331. else
  332. ;
  333. end;
  334. InstrReadsFlags := false;
  335. end;
  336. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  337. begin
  338. Next:=Current;
  339. repeat
  340. Result:=GetNextInstruction(Next,Next);
  341. until not (Result) or
  342. not(cs_opt_level3 in current_settings.optimizerswitches) or
  343. (Next.typ<>ait_instruction) or
  344. RegInInstruction(reg,Next) or
  345. is_calljmp(taicpu(Next).opcode);
  346. end;
  347. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  348. begin
  349. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  350. Next := Current;
  351. repeat
  352. Result := GetNextInstruction(Next,Next);
  353. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  354. if is_calljmpuncondret(taicpu(Next).opcode) then
  355. begin
  356. Result := False;
  357. Exit;
  358. end
  359. else
  360. CrossJump := True;
  361. until not Result or
  362. not (cs_opt_level3 in current_settings.optimizerswitches) or
  363. (Next.typ <> ait_instruction) or
  364. RegInInstruction(reg,Next);
  365. end;
  366. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  367. begin
  368. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  369. begin
  370. Result:=GetNextInstruction(Current,Next);
  371. exit;
  372. end;
  373. Next:=tai(Current.Next);
  374. Result:=false;
  375. while assigned(Next) do
  376. begin
  377. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  378. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  379. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  380. exit
  381. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  382. begin
  383. Result:=true;
  384. exit;
  385. end;
  386. Next:=tai(Next.Next);
  387. end;
  388. end;
  389. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  390. begin
  391. Result:=RegReadByInstruction(reg,hp);
  392. end;
  393. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  394. var
  395. p: taicpu;
  396. opcount: longint;
  397. begin
  398. RegReadByInstruction := false;
  399. if hp.typ <> ait_instruction then
  400. exit;
  401. p := taicpu(hp);
  402. case p.opcode of
  403. A_CALL:
  404. regreadbyinstruction := true;
  405. A_IMUL:
  406. case p.ops of
  407. 1:
  408. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  409. (
  410. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  411. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  412. );
  413. 2,3:
  414. regReadByInstruction :=
  415. reginop(reg,p.oper[0]^) or
  416. reginop(reg,p.oper[1]^);
  417. else
  418. InternalError(2019112801);
  419. end;
  420. A_MUL:
  421. begin
  422. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  423. (
  424. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  425. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  426. );
  427. end;
  428. A_IDIV,A_DIV:
  429. begin
  430. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  431. (
  432. (getregtype(reg)=R_INTREGISTER) and
  433. (
  434. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  435. )
  436. );
  437. end;
  438. else
  439. begin
  440. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  441. begin
  442. RegReadByInstruction := false;
  443. exit;
  444. end;
  445. for opcount := 0 to p.ops-1 do
  446. if (p.oper[opCount]^.typ = top_ref) and
  447. RegInRef(reg,p.oper[opcount]^.ref^) then
  448. begin
  449. RegReadByInstruction := true;
  450. exit
  451. end;
  452. { special handling for SSE MOVSD }
  453. if (p.opcode=A_MOVSD) and (p.ops>0) then
  454. begin
  455. if p.ops<>2 then
  456. internalerror(2017042702);
  457. regReadByInstruction := reginop(reg,p.oper[0]^) or
  458. (
  459. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  460. );
  461. exit;
  462. end;
  463. with insprop[p.opcode] do
  464. begin
  465. case getregtype(reg) of
  466. R_INTREGISTER:
  467. begin
  468. case getsupreg(reg) of
  469. RS_EAX:
  470. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  471. begin
  472. RegReadByInstruction := true;
  473. exit
  474. end;
  475. RS_ECX:
  476. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  477. begin
  478. RegReadByInstruction := true;
  479. exit
  480. end;
  481. RS_EDX:
  482. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  483. begin
  484. RegReadByInstruction := true;
  485. exit
  486. end;
  487. RS_EBX:
  488. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  489. begin
  490. RegReadByInstruction := true;
  491. exit
  492. end;
  493. RS_ESP:
  494. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  495. begin
  496. RegReadByInstruction := true;
  497. exit
  498. end;
  499. RS_EBP:
  500. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  501. begin
  502. RegReadByInstruction := true;
  503. exit
  504. end;
  505. RS_ESI:
  506. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  507. begin
  508. RegReadByInstruction := true;
  509. exit
  510. end;
  511. RS_EDI:
  512. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  513. begin
  514. RegReadByInstruction := true;
  515. exit
  516. end;
  517. end;
  518. end;
  519. R_MMREGISTER:
  520. begin
  521. case getsupreg(reg) of
  522. RS_XMM0:
  523. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  524. begin
  525. RegReadByInstruction := true;
  526. exit
  527. end;
  528. end;
  529. end;
  530. else
  531. ;
  532. end;
  533. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  534. begin
  535. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  536. begin
  537. case p.condition of
  538. C_A,C_NBE, { CF=0 and ZF=0 }
  539. C_BE,C_NA: { CF=1 or ZF=1 }
  540. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  541. C_AE,C_NB,C_NC, { CF=0 }
  542. C_B,C_NAE,C_C: { CF=1 }
  543. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  544. C_NE,C_NZ, { ZF=0 }
  545. C_E,C_Z: { ZF=1 }
  546. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  547. C_G,C_NLE, { ZF=0 and SF=OF }
  548. C_LE,C_NG: { ZF=1 or SF<>OF }
  549. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  550. C_GE,C_NL, { SF=OF }
  551. C_L,C_NGE: { SF<>OF }
  552. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  553. C_NO, { OF=0 }
  554. C_O: { OF=1 }
  555. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  556. C_NP,C_PO, { PF=0 }
  557. C_P,C_PE: { PF=1 }
  558. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  559. C_NS, { SF=0 }
  560. C_S: { SF=1 }
  561. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  562. else
  563. internalerror(2017042701);
  564. end;
  565. if RegReadByInstruction then
  566. exit;
  567. end;
  568. case getsubreg(reg) of
  569. R_SUBW,R_SUBD,R_SUBQ:
  570. RegReadByInstruction :=
  571. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  572. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  573. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  574. R_SUBFLAGCARRY:
  575. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  576. R_SUBFLAGPARITY:
  577. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  578. R_SUBFLAGAUXILIARY:
  579. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  580. R_SUBFLAGZERO:
  581. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  582. R_SUBFLAGSIGN:
  583. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  584. R_SUBFLAGOVERFLOW:
  585. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  586. R_SUBFLAGINTERRUPT:
  587. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  588. R_SUBFLAGDIRECTION:
  589. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  590. else
  591. internalerror(2017042601);
  592. end;
  593. exit;
  594. end;
  595. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  596. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  597. (p.oper[0]^.reg=p.oper[1]^.reg) then
  598. exit;
  599. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  600. begin
  601. RegReadByInstruction := true;
  602. exit
  603. end;
  604. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  605. begin
  606. RegReadByInstruction := true;
  607. exit
  608. end;
  609. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  610. begin
  611. RegReadByInstruction := true;
  612. exit
  613. end;
  614. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  615. begin
  616. RegReadByInstruction := true;
  617. exit
  618. end;
  619. end;
  620. end;
  621. end;
  622. end;
  623. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  624. begin
  625. result:=false;
  626. if p1.typ<>ait_instruction then
  627. exit;
  628. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  629. exit(true);
  630. if (getregtype(reg)=R_INTREGISTER) and
  631. { change information for xmm movsd are not correct }
  632. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  633. begin
  634. case getsupreg(reg) of
  635. { RS_EAX = RS_RAX on x86-64 }
  636. RS_EAX:
  637. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  638. RS_ECX:
  639. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  640. RS_EDX:
  641. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  642. RS_EBX:
  643. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  644. RS_ESP:
  645. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  646. RS_EBP:
  647. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  648. RS_ESI:
  649. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  650. RS_EDI:
  651. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  652. else
  653. ;
  654. end;
  655. if result then
  656. exit;
  657. end
  658. else if getregtype(reg)=R_MMREGISTER then
  659. begin
  660. case getsupreg(reg) of
  661. RS_XMM0:
  662. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  663. else
  664. ;
  665. end;
  666. if result then
  667. exit;
  668. end
  669. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  670. begin
  671. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  672. exit(true);
  673. case getsubreg(reg) of
  674. R_SUBFLAGCARRY:
  675. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  676. R_SUBFLAGPARITY:
  677. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  678. R_SUBFLAGAUXILIARY:
  679. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  680. R_SUBFLAGZERO:
  681. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  682. R_SUBFLAGSIGN:
  683. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  684. R_SUBFLAGOVERFLOW:
  685. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  686. R_SUBFLAGINTERRUPT:
  687. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  688. R_SUBFLAGDIRECTION:
  689. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  690. R_SUBW,R_SUBD,R_SUBQ:
  691. { Everything except the direction bits }
  692. Result:=
  693. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  694. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  695. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  696. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  697. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  698. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  699. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  700. else
  701. ;
  702. end;
  703. if result then
  704. exit;
  705. end
  706. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  707. exit(true);
  708. Result:=inherited RegInInstruction(Reg, p1);
  709. end;
  710. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  711. const
  712. WriteOps: array[0..3] of set of TInsChange =
  713. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  714. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  715. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  716. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  717. var
  718. OperIdx: Integer;
  719. begin
  720. Result := False;
  721. if p1.typ <> ait_instruction then
  722. exit;
  723. with insprop[taicpu(p1).opcode] do
  724. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  725. begin
  726. case getsubreg(reg) of
  727. R_SUBW,R_SUBD,R_SUBQ:
  728. Result :=
  729. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  730. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  731. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  732. R_SUBFLAGCARRY:
  733. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  734. R_SUBFLAGPARITY:
  735. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  736. R_SUBFLAGAUXILIARY:
  737. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  738. R_SUBFLAGZERO:
  739. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  740. R_SUBFLAGSIGN:
  741. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  742. R_SUBFLAGOVERFLOW:
  743. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  744. R_SUBFLAGINTERRUPT:
  745. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  746. R_SUBFLAGDIRECTION:
  747. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  748. else
  749. internalerror(2017042602);
  750. end;
  751. exit;
  752. end;
  753. case taicpu(p1).opcode of
  754. A_CALL:
  755. { We could potentially set Result to False if the register in
  756. question is non-volatile for the subroutine's calling convention,
  757. but this would require detecting the calling convention in use and
  758. also assuming that the routine doesn't contain malformed assembly
  759. language, for example... so it could only be done under -O4 as it
  760. would be considered a side-effect. [Kit] }
  761. Result := True;
  762. A_MOVSD:
  763. { special handling for SSE MOVSD }
  764. if (taicpu(p1).ops>0) then
  765. begin
  766. if taicpu(p1).ops<>2 then
  767. internalerror(2017042703);
  768. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  769. end;
  770. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  771. so fix it here (FK)
  772. }
  773. A_VMOVSS,
  774. A_VMOVSD:
  775. begin
  776. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  777. exit;
  778. end;
  779. A_IMUL:
  780. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  781. else
  782. ;
  783. end;
  784. if Result then
  785. exit;
  786. with insprop[taicpu(p1).opcode] do
  787. begin
  788. if getregtype(reg)=R_INTREGISTER then
  789. begin
  790. case getsupreg(reg) of
  791. RS_EAX:
  792. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  793. begin
  794. Result := True;
  795. exit
  796. end;
  797. RS_ECX:
  798. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  799. begin
  800. Result := True;
  801. exit
  802. end;
  803. RS_EDX:
  804. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  805. begin
  806. Result := True;
  807. exit
  808. end;
  809. RS_EBX:
  810. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  811. begin
  812. Result := True;
  813. exit
  814. end;
  815. RS_ESP:
  816. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  817. begin
  818. Result := True;
  819. exit
  820. end;
  821. RS_EBP:
  822. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  823. begin
  824. Result := True;
  825. exit
  826. end;
  827. RS_ESI:
  828. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  829. begin
  830. Result := True;
  831. exit
  832. end;
  833. RS_EDI:
  834. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  835. begin
  836. Result := True;
  837. exit
  838. end;
  839. end;
  840. end;
  841. for OperIdx := 0 to taicpu(p1).ops - 1 do
  842. if (WriteOps[OperIdx]*Ch<>[]) and
  843. { The register doesn't get modified inside a reference }
  844. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  845. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  846. begin
  847. Result := true;
  848. exit
  849. end;
  850. end;
  851. end;
  852. {$ifdef DEBUG_AOPTCPU}
  853. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  854. begin
  855. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  856. end;
  857. function debug_tostr(i: tcgint): string; inline;
  858. begin
  859. Result := tostr(i);
  860. end;
  861. function debug_regname(r: TRegister): string; inline;
  862. begin
  863. Result := '%' + std_regname(r);
  864. end;
  865. { Debug output function - creates a string representation of an operator }
  866. function debug_operstr(oper: TOper): string;
  867. begin
  868. case oper.typ of
  869. top_const:
  870. Result := '$' + debug_tostr(oper.val);
  871. top_reg:
  872. Result := debug_regname(oper.reg);
  873. top_ref:
  874. begin
  875. if oper.ref^.offset <> 0 then
  876. Result := debug_tostr(oper.ref^.offset) + '('
  877. else
  878. Result := '(';
  879. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  880. begin
  881. Result := Result + debug_regname(oper.ref^.base);
  882. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  883. Result := Result + ',' + debug_regname(oper.ref^.index);
  884. end
  885. else
  886. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  887. Result := Result + debug_regname(oper.ref^.index);
  888. if (oper.ref^.scalefactor > 1) then
  889. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  890. else
  891. Result := Result + ')';
  892. end;
  893. else
  894. Result := '[UNKNOWN]';
  895. end;
  896. end;
  897. function debug_op2str(opcode: tasmop): string; inline;
  898. begin
  899. Result := std_op2str[opcode];
  900. end;
  901. function debug_opsize2str(opsize: topsize): string; inline;
  902. begin
  903. Result := gas_opsize2str[opsize];
  904. end;
  905. {$else DEBUG_AOPTCPU}
  906. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  907. begin
  908. end;
  909. function debug_tostr(i: tcgint): string; inline;
  910. begin
  911. Result := '';
  912. end;
  913. function debug_regname(r: TRegister): string; inline;
  914. begin
  915. Result := '';
  916. end;
  917. function debug_operstr(oper: TOper): string; inline;
  918. begin
  919. Result := '';
  920. end;
  921. function debug_op2str(opcode: tasmop): string; inline;
  922. begin
  923. Result := '';
  924. end;
  925. function debug_opsize2str(opsize: topsize): string; inline;
  926. begin
  927. Result := '';
  928. end;
  929. {$endif DEBUG_AOPTCPU}
  930. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  931. begin
  932. {$ifdef x86_64}
  933. { Always fine on x86-64 }
  934. Result := True;
  935. {$else x86_64}
  936. Result :=
  937. {$ifdef i8086}
  938. (current_settings.cputype >= cpu_386) and
  939. {$endif i8086}
  940. (
  941. { Always accept if optimising for size }
  942. (cs_opt_size in current_settings.optimizerswitches) or
  943. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  944. (current_settings.optimizecputype >= cpu_Pentium2)
  945. );
  946. {$endif x86_64}
  947. end;
  948. { Attempts to allocate a volatile integer register for use between p and hp,
  949. using AUsedRegs for the current register usage information. Returns NR_NO
  950. if no free register could be found }
  951. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  952. var
  953. RegSet: TCPURegisterSet;
  954. CurrentSuperReg: Integer;
  955. CurrentReg: TRegister;
  956. Currentp: tai;
  957. Breakout: Boolean;
  958. begin
  959. Result := NR_NO;
  960. RegSet :=
  961. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  962. current_procinfo.saved_regs_int;
  963. for CurrentSuperReg in RegSet do
  964. begin
  965. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  966. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  967. {$if defined(i386) or defined(i8086)}
  968. { If the target size is 8-bit, make sure we can actually encode it }
  969. and (
  970. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  971. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  972. )
  973. {$endif i386 or i8086}
  974. then
  975. begin
  976. Currentp := p;
  977. Breakout := False;
  978. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  979. begin
  980. case Currentp.typ of
  981. ait_instruction:
  982. begin
  983. if RegInInstruction(CurrentReg, Currentp) then
  984. begin
  985. Breakout := True;
  986. Break;
  987. end;
  988. { Cannot allocate across an unconditional jump }
  989. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  990. Exit;
  991. end;
  992. ait_marker:
  993. { Don't try anything more if a marker is hit }
  994. Exit;
  995. ait_regalloc:
  996. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  997. begin
  998. Breakout := True;
  999. Break;
  1000. end;
  1001. else
  1002. ;
  1003. end;
  1004. end;
  1005. if Breakout then
  1006. { Try the next register }
  1007. Continue;
  1008. { We have a free register available }
  1009. Result := CurrentReg;
  1010. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1011. Exit;
  1012. end;
  1013. end;
  1014. end;
  1015. { Attempts to allocate a volatile MM register for use between p and hp,
  1016. using AUsedRegs for the current register usage information. Returns NR_NO
  1017. if no free register could be found }
  1018. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1019. var
  1020. RegSet: TCPURegisterSet;
  1021. CurrentSuperReg: Integer;
  1022. CurrentReg: TRegister;
  1023. Currentp: tai;
  1024. Breakout: Boolean;
  1025. begin
  1026. Result := NR_NO;
  1027. RegSet :=
  1028. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1029. current_procinfo.saved_regs_mm;
  1030. for CurrentSuperReg in RegSet do
  1031. begin
  1032. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1033. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1034. begin
  1035. Currentp := p;
  1036. Breakout := False;
  1037. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1038. begin
  1039. case Currentp.typ of
  1040. ait_instruction:
  1041. begin
  1042. if RegInInstruction(CurrentReg, Currentp) then
  1043. begin
  1044. Breakout := True;
  1045. Break;
  1046. end;
  1047. { Cannot allocate across an unconditional jump }
  1048. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1049. Exit;
  1050. end;
  1051. ait_marker:
  1052. { Don't try anything more if a marker is hit }
  1053. Exit;
  1054. ait_regalloc:
  1055. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1056. begin
  1057. Breakout := True;
  1058. Break;
  1059. end;
  1060. else
  1061. ;
  1062. end;
  1063. end;
  1064. if Breakout then
  1065. { Try the next register }
  1066. Continue;
  1067. { We have a free register available }
  1068. Result := CurrentReg;
  1069. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1070. Exit;
  1071. end;
  1072. end;
  1073. end;
  1074. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1075. begin
  1076. if not SuperRegistersEqual(reg1,reg2) then
  1077. exit(false);
  1078. if getregtype(reg1)<>R_INTREGISTER then
  1079. exit(true); {because SuperRegisterEqual is true}
  1080. case getsubreg(reg1) of
  1081. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1082. higher, it preserves the high bits, so the new value depends on
  1083. reg2's previous value. In other words, it is equivalent to doing:
  1084. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1085. R_SUBL:
  1086. exit(getsubreg(reg2)=R_SUBL);
  1087. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1088. higher, it actually does a:
  1089. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1090. R_SUBH:
  1091. exit(getsubreg(reg2)=R_SUBH);
  1092. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1093. bits of reg2:
  1094. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1095. R_SUBW:
  1096. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1097. { a write to R_SUBD always overwrites every other subregister,
  1098. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1099. R_SUBD,
  1100. R_SUBQ:
  1101. exit(true);
  1102. else
  1103. internalerror(2017042801);
  1104. end;
  1105. end;
  1106. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1107. begin
  1108. if not SuperRegistersEqual(reg1,reg2) then
  1109. exit(false);
  1110. if getregtype(reg1)<>R_INTREGISTER then
  1111. exit(true); {because SuperRegisterEqual is true}
  1112. case getsubreg(reg1) of
  1113. R_SUBL:
  1114. exit(getsubreg(reg2)<>R_SUBH);
  1115. R_SUBH:
  1116. exit(getsubreg(reg2)<>R_SUBL);
  1117. R_SUBW,
  1118. R_SUBD,
  1119. R_SUBQ:
  1120. exit(true);
  1121. else
  1122. internalerror(2017042802);
  1123. end;
  1124. end;
  1125. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1126. var
  1127. hp1 : tai;
  1128. l : TCGInt;
  1129. begin
  1130. result:=false;
  1131. { changes the code sequence
  1132. shr/sar const1, x
  1133. shl const2, x
  1134. to
  1135. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1136. if GetNextInstruction(p, hp1) and
  1137. MatchInstruction(hp1,A_SHL,[]) and
  1138. (taicpu(p).oper[0]^.typ = top_const) and
  1139. (taicpu(hp1).oper[0]^.typ = top_const) and
  1140. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1141. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1142. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1143. begin
  1144. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1145. not(cs_opt_size in current_settings.optimizerswitches) then
  1146. begin
  1147. { shr/sar const1, %reg
  1148. shl const2, %reg
  1149. with const1 > const2 }
  1150. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1151. taicpu(hp1).opcode := A_AND;
  1152. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1153. case taicpu(p).opsize Of
  1154. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1155. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1156. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1157. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1158. else
  1159. Internalerror(2017050703)
  1160. end;
  1161. end
  1162. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1163. not(cs_opt_size in current_settings.optimizerswitches) then
  1164. begin
  1165. { shr/sar const1, %reg
  1166. shl const2, %reg
  1167. with const1 < const2 }
  1168. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1169. taicpu(p).opcode := A_AND;
  1170. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1171. case taicpu(p).opsize Of
  1172. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1173. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1174. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1175. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1176. else
  1177. Internalerror(2017050702)
  1178. end;
  1179. end
  1180. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1181. begin
  1182. { shr/sar const1, %reg
  1183. shl const2, %reg
  1184. with const1 = const2 }
  1185. taicpu(p).opcode := A_AND;
  1186. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1187. case taicpu(p).opsize Of
  1188. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1189. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1190. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1191. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1192. else
  1193. Internalerror(2017050701)
  1194. end;
  1195. RemoveInstruction(hp1);
  1196. end;
  1197. end;
  1198. end;
  1199. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1200. var
  1201. opsize : topsize;
  1202. hp1 : tai;
  1203. tmpref : treference;
  1204. ShiftValue : Cardinal;
  1205. BaseValue : TCGInt;
  1206. begin
  1207. result:=false;
  1208. opsize:=taicpu(p).opsize;
  1209. { changes certain "imul const, %reg"'s to lea sequences }
  1210. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1211. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1212. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1213. if (taicpu(p).oper[0]^.val = 1) then
  1214. if (taicpu(p).ops = 2) then
  1215. { remove "imul $1, reg" }
  1216. begin
  1217. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1218. Result := RemoveCurrentP(p);
  1219. end
  1220. else
  1221. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1222. begin
  1223. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1224. InsertLLItem(p.previous, p.next, hp1);
  1225. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1226. p.free;
  1227. p := hp1;
  1228. end
  1229. else if ((taicpu(p).ops <= 2) or
  1230. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1231. not(cs_opt_size in current_settings.optimizerswitches) and
  1232. (not(GetNextInstruction(p, hp1)) or
  1233. not((tai(hp1).typ = ait_instruction) and
  1234. ((taicpu(hp1).opcode=A_Jcc) and
  1235. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1236. begin
  1237. {
  1238. imul X, reg1, reg2 to
  1239. lea (reg1,reg1,Y), reg2
  1240. shl ZZ,reg2
  1241. imul XX, reg1 to
  1242. lea (reg1,reg1,YY), reg1
  1243. shl ZZ,reg2
  1244. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1245. it does not exist as a separate optimization target in FPC though.
  1246. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1247. at most two zeros
  1248. }
  1249. reference_reset(tmpref,1,[]);
  1250. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1251. begin
  1252. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1253. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1254. TmpRef.base := taicpu(p).oper[1]^.reg;
  1255. TmpRef.index := taicpu(p).oper[1]^.reg;
  1256. if not(BaseValue in [3,5,9]) then
  1257. Internalerror(2018110101);
  1258. TmpRef.ScaleFactor := BaseValue-1;
  1259. if (taicpu(p).ops = 2) then
  1260. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1261. else
  1262. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1263. AsmL.InsertAfter(hp1,p);
  1264. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1265. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1266. RemoveCurrentP(p, hp1);
  1267. if ShiftValue>0 then
  1268. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1269. end;
  1270. end;
  1271. end;
  1272. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1273. begin
  1274. Result := False;
  1275. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1276. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1277. begin
  1278. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1279. taicpu(p).opcode := A_MOV;
  1280. Result := True;
  1281. end;
  1282. end;
  1283. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1284. var
  1285. p: taicpu absolute hp; { Implicit typecast }
  1286. i: Integer;
  1287. begin
  1288. Result := False;
  1289. if not assigned(hp) or
  1290. (hp.typ <> ait_instruction) then
  1291. Exit;
  1292. Prefetch(insprop[p.opcode]);
  1293. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1294. with insprop[p.opcode] do
  1295. begin
  1296. case getsubreg(reg) of
  1297. R_SUBW,R_SUBD,R_SUBQ:
  1298. Result:=
  1299. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1300. uncommon flags are checked first }
  1301. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1302. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1303. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1304. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1305. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1306. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1307. R_SUBFLAGCARRY:
  1308. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1309. R_SUBFLAGPARITY:
  1310. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1311. R_SUBFLAGAUXILIARY:
  1312. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1313. R_SUBFLAGZERO:
  1314. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1315. R_SUBFLAGSIGN:
  1316. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1317. R_SUBFLAGOVERFLOW:
  1318. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1319. R_SUBFLAGINTERRUPT:
  1320. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1321. R_SUBFLAGDIRECTION:
  1322. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1323. else
  1324. internalerror(2017050501);
  1325. end;
  1326. exit;
  1327. end;
  1328. { Handle special cases first }
  1329. case p.opcode of
  1330. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1331. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1332. begin
  1333. Result :=
  1334. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1335. (p.oper[1]^.typ = top_reg) and
  1336. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1337. (
  1338. (p.oper[0]^.typ = top_const) or
  1339. (
  1340. (p.oper[0]^.typ = top_reg) and
  1341. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1342. ) or (
  1343. (p.oper[0]^.typ = top_ref) and
  1344. not RegInRef(reg,p.oper[0]^.ref^)
  1345. )
  1346. );
  1347. end;
  1348. A_MUL, A_IMUL:
  1349. Result :=
  1350. (
  1351. (p.ops=3) and { IMUL only }
  1352. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1353. (
  1354. (
  1355. (p.oper[1]^.typ=top_reg) and
  1356. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1357. ) or (
  1358. (p.oper[1]^.typ=top_ref) and
  1359. not RegInRef(reg,p.oper[1]^.ref^)
  1360. )
  1361. )
  1362. ) or (
  1363. (
  1364. (p.ops=1) and
  1365. (
  1366. (
  1367. (
  1368. (p.oper[0]^.typ=top_reg) and
  1369. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1370. )
  1371. ) or (
  1372. (p.oper[0]^.typ=top_ref) and
  1373. not RegInRef(reg,p.oper[0]^.ref^)
  1374. )
  1375. ) and (
  1376. (
  1377. (p.opsize=S_B) and
  1378. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1379. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1380. ) or (
  1381. (p.opsize=S_W) and
  1382. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1383. ) or (
  1384. (p.opsize=S_L) and
  1385. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1386. {$ifdef x86_64}
  1387. ) or (
  1388. (p.opsize=S_Q) and
  1389. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1390. {$endif x86_64}
  1391. )
  1392. )
  1393. )
  1394. );
  1395. A_CBW:
  1396. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1397. {$ifndef x86_64}
  1398. A_LDS:
  1399. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1400. A_LES:
  1401. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1402. {$endif not x86_64}
  1403. A_LFS:
  1404. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1405. A_LGS:
  1406. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1407. A_LSS:
  1408. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1409. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1410. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1411. A_LODSB:
  1412. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1413. A_LODSW:
  1414. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1415. {$ifdef x86_64}
  1416. A_LODSQ:
  1417. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1418. {$endif x86_64}
  1419. A_LODSD:
  1420. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1421. A_FSTSW, A_FNSTSW:
  1422. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1423. else
  1424. begin
  1425. with insprop[p.opcode] do
  1426. begin
  1427. if (
  1428. { xor %reg,%reg etc. is classed as a new value }
  1429. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1430. MatchOpType(p, top_reg, top_reg) and
  1431. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1432. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1433. ) then
  1434. begin
  1435. Result := True;
  1436. Exit;
  1437. end;
  1438. { Make sure the entire register is overwritten }
  1439. if (getregtype(reg) = R_INTREGISTER) then
  1440. begin
  1441. if (p.ops > 0) then
  1442. begin
  1443. if RegInOp(reg, p.oper[0]^) then
  1444. begin
  1445. if (p.oper[0]^.typ = top_ref) then
  1446. begin
  1447. if RegInRef(reg, p.oper[0]^.ref^) then
  1448. begin
  1449. Result := False;
  1450. Exit;
  1451. end;
  1452. end
  1453. else if (p.oper[0]^.typ = top_reg) then
  1454. begin
  1455. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1456. begin
  1457. Result := False;
  1458. Exit;
  1459. end
  1460. else if ([Ch_WOp1]*Ch<>[]) then
  1461. begin
  1462. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1463. Result := True
  1464. else
  1465. begin
  1466. Result := False;
  1467. Exit;
  1468. end;
  1469. end;
  1470. end;
  1471. end;
  1472. if (p.ops > 1) then
  1473. begin
  1474. if RegInOp(reg, p.oper[1]^) then
  1475. begin
  1476. if (p.oper[1]^.typ = top_ref) then
  1477. begin
  1478. if RegInRef(reg, p.oper[1]^.ref^) then
  1479. begin
  1480. Result := False;
  1481. Exit;
  1482. end;
  1483. end
  1484. else if (p.oper[1]^.typ = top_reg) then
  1485. begin
  1486. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1487. begin
  1488. Result := False;
  1489. Exit;
  1490. end
  1491. else if ([Ch_WOp2]*Ch<>[]) then
  1492. begin
  1493. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1494. Result := True
  1495. else
  1496. begin
  1497. Result := False;
  1498. Exit;
  1499. end;
  1500. end;
  1501. end;
  1502. end;
  1503. if (p.ops > 2) then
  1504. begin
  1505. if RegInOp(reg, p.oper[2]^) then
  1506. begin
  1507. if (p.oper[2]^.typ = top_ref) then
  1508. begin
  1509. if RegInRef(reg, p.oper[2]^.ref^) then
  1510. begin
  1511. Result := False;
  1512. Exit;
  1513. end;
  1514. end
  1515. else if (p.oper[2]^.typ = top_reg) then
  1516. begin
  1517. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1518. begin
  1519. Result := False;
  1520. Exit;
  1521. end
  1522. else if ([Ch_WOp3]*Ch<>[]) then
  1523. begin
  1524. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1525. Result := True
  1526. else
  1527. begin
  1528. Result := False;
  1529. Exit;
  1530. end;
  1531. end;
  1532. end;
  1533. end;
  1534. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1535. begin
  1536. if (p.oper[3]^.typ = top_ref) then
  1537. begin
  1538. if RegInRef(reg, p.oper[3]^.ref^) then
  1539. begin
  1540. Result := False;
  1541. Exit;
  1542. end;
  1543. end
  1544. else if (p.oper[3]^.typ = top_reg) then
  1545. begin
  1546. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1547. begin
  1548. Result := False;
  1549. Exit;
  1550. end
  1551. else if ([Ch_WOp4]*Ch<>[]) then
  1552. begin
  1553. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1554. Result := True
  1555. else
  1556. begin
  1557. Result := False;
  1558. Exit;
  1559. end;
  1560. end;
  1561. end;
  1562. end;
  1563. end;
  1564. end;
  1565. end;
  1566. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1567. case getsupreg(reg) of
  1568. RS_EAX:
  1569. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1570. begin
  1571. Result := True;
  1572. Exit;
  1573. end;
  1574. RS_ECX:
  1575. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1576. begin
  1577. Result := True;
  1578. Exit;
  1579. end;
  1580. RS_EDX:
  1581. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1582. begin
  1583. Result := True;
  1584. Exit;
  1585. end;
  1586. RS_EBX:
  1587. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1588. begin
  1589. Result := True;
  1590. Exit;
  1591. end;
  1592. RS_ESP:
  1593. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1594. begin
  1595. Result := True;
  1596. Exit;
  1597. end;
  1598. RS_EBP:
  1599. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1600. begin
  1601. Result := True;
  1602. Exit;
  1603. end;
  1604. RS_ESI:
  1605. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1606. begin
  1607. Result := True;
  1608. Exit;
  1609. end;
  1610. RS_EDI:
  1611. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1612. begin
  1613. Result := True;
  1614. Exit;
  1615. end;
  1616. else
  1617. ;
  1618. end;
  1619. end;
  1620. end;
  1621. end;
  1622. end;
  1623. end;
  1624. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1625. var
  1626. hp2,hp3 : tai;
  1627. begin
  1628. { some x86-64 issue a NOP before the real exit code }
  1629. if MatchInstruction(p,A_NOP,[]) then
  1630. GetNextInstruction(p,p);
  1631. result:=assigned(p) and (p.typ=ait_instruction) and
  1632. ((taicpu(p).opcode = A_RET) or
  1633. ((taicpu(p).opcode=A_LEAVE) and
  1634. GetNextInstruction(p,hp2) and
  1635. MatchInstruction(hp2,A_RET,[S_NO])
  1636. ) or
  1637. (((taicpu(p).opcode=A_LEA) and
  1638. MatchOpType(taicpu(p),top_ref,top_reg) and
  1639. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1640. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1641. ) and
  1642. GetNextInstruction(p,hp2) and
  1643. MatchInstruction(hp2,A_RET,[S_NO])
  1644. ) or
  1645. ((((taicpu(p).opcode=A_MOV) and
  1646. MatchOpType(taicpu(p),top_reg,top_reg) and
  1647. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1648. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1649. ((taicpu(p).opcode=A_LEA) and
  1650. MatchOpType(taicpu(p),top_ref,top_reg) and
  1651. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1652. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1653. )
  1654. ) and
  1655. GetNextInstruction(p,hp2) and
  1656. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1657. MatchOpType(taicpu(hp2),top_reg) and
  1658. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1659. GetNextInstruction(hp2,hp3) and
  1660. MatchInstruction(hp3,A_RET,[S_NO])
  1661. )
  1662. );
  1663. end;
  1664. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1665. begin
  1666. isFoldableArithOp := False;
  1667. case hp1.opcode of
  1668. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1669. isFoldableArithOp :=
  1670. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1671. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1672. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1673. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1674. (taicpu(hp1).oper[1]^.reg = reg);
  1675. A_INC,A_DEC,A_NEG,A_NOT:
  1676. isFoldableArithOp :=
  1677. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1678. (taicpu(hp1).oper[0]^.reg = reg);
  1679. else
  1680. ;
  1681. end;
  1682. end;
  1683. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1684. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1685. var
  1686. hp2: tai;
  1687. begin
  1688. hp2 := p;
  1689. repeat
  1690. hp2 := tai(hp2.previous);
  1691. if assigned(hp2) and
  1692. (hp2.typ = ait_regalloc) and
  1693. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1694. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1695. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1696. begin
  1697. RemoveInstruction(hp2);
  1698. break;
  1699. end;
  1700. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1701. end;
  1702. begin
  1703. case current_procinfo.procdef.returndef.typ of
  1704. arraydef,recorddef,pointerdef,
  1705. stringdef,enumdef,procdef,objectdef,errordef,
  1706. filedef,setdef,procvardef,
  1707. classrefdef,forwarddef:
  1708. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1709. orddef:
  1710. if current_procinfo.procdef.returndef.size <> 0 then
  1711. begin
  1712. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1713. { for int64/qword }
  1714. if current_procinfo.procdef.returndef.size = 8 then
  1715. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1716. end;
  1717. else
  1718. ;
  1719. end;
  1720. end;
  1721. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1722. var
  1723. hp1,hp2 : tai;
  1724. begin
  1725. result:=false;
  1726. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1727. begin
  1728. { vmova* reg1,reg1
  1729. =>
  1730. <nop> }
  1731. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1732. begin
  1733. RemoveCurrentP(p);
  1734. result:=true;
  1735. exit;
  1736. end
  1737. else if GetNextInstruction(p,hp1) then
  1738. begin
  1739. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1740. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1741. begin
  1742. { vmova* reg1,reg2
  1743. vmova* reg2,reg3
  1744. dealloc reg2
  1745. =>
  1746. vmova* reg1,reg3 }
  1747. TransferUsedRegs(TmpUsedRegs);
  1748. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1749. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1750. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1751. begin
  1752. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1753. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1754. RemoveInstruction(hp1);
  1755. result:=true;
  1756. exit;
  1757. end
  1758. { special case:
  1759. vmova* reg1,<op>
  1760. vmova* <op>,reg1
  1761. =>
  1762. vmova* reg1,<op> }
  1763. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1764. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1765. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1766. ) then
  1767. begin
  1768. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1769. RemoveInstruction(hp1);
  1770. result:=true;
  1771. exit;
  1772. end
  1773. end
  1774. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1775. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1776. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1777. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1778. ) and
  1779. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1780. begin
  1781. { vmova* reg1,reg2
  1782. vmovs* reg2,<op>
  1783. dealloc reg2
  1784. =>
  1785. vmovs* reg1,reg3 }
  1786. TransferUsedRegs(TmpUsedRegs);
  1787. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1788. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1789. begin
  1790. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1791. taicpu(p).opcode:=taicpu(hp1).opcode;
  1792. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1793. RemoveInstruction(hp1);
  1794. result:=true;
  1795. exit;
  1796. end
  1797. end;
  1798. end;
  1799. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1800. begin
  1801. if MatchInstruction(hp1,[A_VFMADDPD,
  1802. A_VFMADD132PD,
  1803. A_VFMADD132PS,
  1804. A_VFMADD132SD,
  1805. A_VFMADD132SS,
  1806. A_VFMADD213PD,
  1807. A_VFMADD213PS,
  1808. A_VFMADD213SD,
  1809. A_VFMADD213SS,
  1810. A_VFMADD231PD,
  1811. A_VFMADD231PS,
  1812. A_VFMADD231SD,
  1813. A_VFMADD231SS,
  1814. A_VFMADDSUB132PD,
  1815. A_VFMADDSUB132PS,
  1816. A_VFMADDSUB213PD,
  1817. A_VFMADDSUB213PS,
  1818. A_VFMADDSUB231PD,
  1819. A_VFMADDSUB231PS,
  1820. A_VFMSUB132PD,
  1821. A_VFMSUB132PS,
  1822. A_VFMSUB132SD,
  1823. A_VFMSUB132SS,
  1824. A_VFMSUB213PD,
  1825. A_VFMSUB213PS,
  1826. A_VFMSUB213SD,
  1827. A_VFMSUB213SS,
  1828. A_VFMSUB231PD,
  1829. A_VFMSUB231PS,
  1830. A_VFMSUB231SD,
  1831. A_VFMSUB231SS,
  1832. A_VFMSUBADD132PD,
  1833. A_VFMSUBADD132PS,
  1834. A_VFMSUBADD213PD,
  1835. A_VFMSUBADD213PS,
  1836. A_VFMSUBADD231PD,
  1837. A_VFMSUBADD231PS,
  1838. A_VFNMADD132PD,
  1839. A_VFNMADD132PS,
  1840. A_VFNMADD132SD,
  1841. A_VFNMADD132SS,
  1842. A_VFNMADD213PD,
  1843. A_VFNMADD213PS,
  1844. A_VFNMADD213SD,
  1845. A_VFNMADD213SS,
  1846. A_VFNMADD231PD,
  1847. A_VFNMADD231PS,
  1848. A_VFNMADD231SD,
  1849. A_VFNMADD231SS,
  1850. A_VFNMSUB132PD,
  1851. A_VFNMSUB132PS,
  1852. A_VFNMSUB132SD,
  1853. A_VFNMSUB132SS,
  1854. A_VFNMSUB213PD,
  1855. A_VFNMSUB213PS,
  1856. A_VFNMSUB213SD,
  1857. A_VFNMSUB213SS,
  1858. A_VFNMSUB231PD,
  1859. A_VFNMSUB231PS,
  1860. A_VFNMSUB231SD,
  1861. A_VFNMSUB231SS],[S_NO]) and
  1862. { we mix single and double opperations here because we assume that the compiler
  1863. generates vmovapd only after double operations and vmovaps only after single operations }
  1864. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1865. GetNextInstruction(hp1,hp2) and
  1866. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1867. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1868. begin
  1869. TransferUsedRegs(TmpUsedRegs);
  1870. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1871. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1872. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1873. begin
  1874. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1875. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1876. RemoveInstruction(hp2);
  1877. end;
  1878. end
  1879. else if (hp1.typ = ait_instruction) and
  1880. GetNextInstruction(hp1, hp2) and
  1881. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1882. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1883. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1884. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1885. (((taicpu(p).opcode=A_MOVAPS) and
  1886. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1887. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1888. ((taicpu(p).opcode=A_MOVAPD) and
  1889. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1890. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1891. ) then
  1892. { change
  1893. movapX reg,reg2
  1894. addsX/subsX/... reg3, reg2
  1895. movapX reg2,reg
  1896. to
  1897. addsX/subsX/... reg3,reg
  1898. }
  1899. begin
  1900. TransferUsedRegs(TmpUsedRegs);
  1901. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1902. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1903. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1904. begin
  1905. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1906. debug_op2str(taicpu(p).opcode)+' '+
  1907. debug_op2str(taicpu(hp1).opcode)+' '+
  1908. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1909. { we cannot eliminate the first move if
  1910. the operations uses the same register for source and dest }
  1911. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1912. RemoveCurrentP(p, nil);
  1913. p:=hp1;
  1914. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1915. RemoveInstruction(hp2);
  1916. result:=true;
  1917. end;
  1918. end
  1919. else if (hp1.typ = ait_instruction) and
  1920. (((taicpu(p).opcode=A_VMOVAPD) and
  1921. (taicpu(hp1).opcode=A_VCOMISD)) or
  1922. ((taicpu(p).opcode=A_VMOVAPS) and
  1923. ((taicpu(hp1).opcode=A_VCOMISS))
  1924. )
  1925. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1926. { change
  1927. movapX reg,reg2
  1928. addsX/subsX/... reg3, reg2
  1929. movapX reg2,reg
  1930. to
  1931. addsX/subsX/... reg3,reg
  1932. }
  1933. begin
  1934. TransferUsedRegs(TmpUsedRegs);
  1935. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1936. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1937. begin
  1938. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  1939. debug_op2str(taicpu(p).opcode)+' '+
  1940. debug_op2str(taicpu(hp1).opcode)+') done',p);
  1941. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1942. taicpu(hp1).loadoper(0, taicpu(p).oper[1]^);
  1943. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  1944. taicpu(hp1).loadoper(1, taicpu(p).oper[1]^);
  1945. RemoveCurrentP(p, nil);
  1946. result:=true;
  1947. exit;
  1948. end;
  1949. end
  1950. end;
  1951. end;
  1952. end;
  1953. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1954. var
  1955. hp1 : tai;
  1956. begin
  1957. result:=false;
  1958. { replace
  1959. V<Op>X %mreg1,%mreg2,%mreg3
  1960. VMovX %mreg3,%mreg4
  1961. dealloc %mreg3
  1962. by
  1963. V<Op>X %mreg1,%mreg2,%mreg4
  1964. ?
  1965. }
  1966. if GetNextInstruction(p,hp1) and
  1967. { we mix single and double operations here because we assume that the compiler
  1968. generates vmovapd only after double operations and vmovaps only after single operations }
  1969. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1970. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1971. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1972. begin
  1973. TransferUsedRegs(TmpUsedRegs);
  1974. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1975. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1976. begin
  1977. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1978. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1979. RemoveInstruction(hp1);
  1980. result:=true;
  1981. end;
  1982. end;
  1983. end;
  1984. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1985. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1986. begin
  1987. Result := False;
  1988. { For safety reasons, only check for exact register matches }
  1989. { Check base register }
  1990. if (ref.base = AOldReg) then
  1991. begin
  1992. ref.base := ANewReg;
  1993. Result := True;
  1994. end;
  1995. { Check index register }
  1996. if (ref.index = AOldReg) then
  1997. begin
  1998. ref.index := ANewReg;
  1999. Result := True;
  2000. end;
  2001. end;
  2002. { Replaces all references to AOldReg in an operand to ANewReg }
  2003. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2004. var
  2005. OldSupReg, NewSupReg: TSuperRegister;
  2006. OldSubReg, NewSubReg: TSubRegister;
  2007. OldRegType: TRegisterType;
  2008. ThisOper: POper;
  2009. begin
  2010. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2011. Result := False;
  2012. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2013. InternalError(2020011801);
  2014. OldSupReg := getsupreg(AOldReg);
  2015. OldSubReg := getsubreg(AOldReg);
  2016. OldRegType := getregtype(AOldReg);
  2017. NewSupReg := getsupreg(ANewReg);
  2018. NewSubReg := getsubreg(ANewReg);
  2019. if OldRegType <> getregtype(ANewReg) then
  2020. InternalError(2020011802);
  2021. if OldSubReg <> NewSubReg then
  2022. InternalError(2020011803);
  2023. case ThisOper^.typ of
  2024. top_reg:
  2025. if (
  2026. (ThisOper^.reg = AOldReg) or
  2027. (
  2028. (OldRegType = R_INTREGISTER) and
  2029. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2030. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2031. (
  2032. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2033. {$ifndef x86_64}
  2034. and (
  2035. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2036. don't have an 8-bit representation }
  2037. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2038. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2039. )
  2040. {$endif x86_64}
  2041. )
  2042. )
  2043. ) then
  2044. begin
  2045. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2046. Result := True;
  2047. end;
  2048. top_ref:
  2049. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2050. Result := True;
  2051. else
  2052. ;
  2053. end;
  2054. end;
  2055. { Replaces all references to AOldReg in an instruction to ANewReg }
  2056. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2057. const
  2058. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2059. var
  2060. OperIdx: Integer;
  2061. begin
  2062. Result := False;
  2063. for OperIdx := 0 to p.ops - 1 do
  2064. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2065. begin
  2066. { The shift and rotate instructions can only use CL }
  2067. if not (
  2068. (OperIdx = 0) and
  2069. { This second condition just helps to avoid unnecessarily
  2070. calling MatchInstruction for 10 different opcodes }
  2071. (p.oper[0]^.reg = NR_CL) and
  2072. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2073. ) then
  2074. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2075. end
  2076. else if p.oper[OperIdx]^.typ = top_ref then
  2077. { It's okay to replace registers in references that get written to }
  2078. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2079. end;
  2080. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2081. begin
  2082. with ref^ do
  2083. Result :=
  2084. (index = NR_NO) and
  2085. (
  2086. {$ifdef x86_64}
  2087. (
  2088. (base = NR_RIP) and
  2089. (refaddr in [addr_pic, addr_pic_no_got])
  2090. ) or
  2091. {$endif x86_64}
  2092. (base = NR_STACK_POINTER_REG) or
  2093. (base = current_procinfo.framepointer)
  2094. );
  2095. end;
  2096. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2097. var
  2098. l: asizeint;
  2099. begin
  2100. Result := False;
  2101. { Should have been checked previously }
  2102. if p.opcode <> A_LEA then
  2103. InternalError(2020072501);
  2104. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2105. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2106. not(cs_opt_size in current_settings.optimizerswitches) then
  2107. exit;
  2108. with p.oper[0]^.ref^ do
  2109. begin
  2110. if (base <> p.oper[1]^.reg) or
  2111. (index <> NR_NO) or
  2112. assigned(symbol) then
  2113. exit;
  2114. l:=offset;
  2115. if (l=1) and UseIncDec then
  2116. begin
  2117. p.opcode:=A_INC;
  2118. p.loadreg(0,p.oper[1]^.reg);
  2119. p.ops:=1;
  2120. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2121. end
  2122. else if (l=-1) and UseIncDec then
  2123. begin
  2124. p.opcode:=A_DEC;
  2125. p.loadreg(0,p.oper[1]^.reg);
  2126. p.ops:=1;
  2127. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2128. end
  2129. else
  2130. begin
  2131. if (l<0) and (l<>-2147483648) then
  2132. begin
  2133. p.opcode:=A_SUB;
  2134. p.loadConst(0,-l);
  2135. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2136. end
  2137. else
  2138. begin
  2139. p.opcode:=A_ADD;
  2140. p.loadConst(0,l);
  2141. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2142. end;
  2143. end;
  2144. end;
  2145. Result := True;
  2146. end;
  2147. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2148. var
  2149. CurrentReg, ReplaceReg: TRegister;
  2150. begin
  2151. Result := False;
  2152. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2153. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2154. case hp.opcode of
  2155. A_FSTSW, A_FNSTSW,
  2156. A_IN, A_INS, A_OUT, A_OUTS,
  2157. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2158. { These routines have explicit operands, but they are restricted in
  2159. what they can be (e.g. IN and OUT can only read from AL, AX or
  2160. EAX. }
  2161. Exit;
  2162. A_IMUL:
  2163. begin
  2164. { The 1-operand version writes to implicit registers
  2165. The 2-operand version reads from the first operator, and reads
  2166. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2167. the 3-operand version reads from a register that it doesn't write to
  2168. }
  2169. case hp.ops of
  2170. 1:
  2171. if (
  2172. (
  2173. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2174. ) or
  2175. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2176. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2177. begin
  2178. Result := True;
  2179. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2180. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2181. end;
  2182. 2:
  2183. { Only modify the first parameter }
  2184. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2185. begin
  2186. Result := True;
  2187. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2188. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2189. end;
  2190. 3:
  2191. { Only modify the second parameter }
  2192. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2193. begin
  2194. Result := True;
  2195. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2196. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2197. end;
  2198. else
  2199. InternalError(2020012901);
  2200. end;
  2201. end;
  2202. else
  2203. if (hp.ops > 0) and
  2204. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2205. begin
  2206. Result := True;
  2207. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2208. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2209. end;
  2210. end;
  2211. end;
  2212. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2213. var
  2214. hp1, hp2, hp3: tai;
  2215. DoOptimisation, TempBool: Boolean;
  2216. {$ifdef x86_64}
  2217. NewConst: TCGInt;
  2218. {$endif x86_64}
  2219. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2220. begin
  2221. if taicpu(hp1).opcode = signed_movop then
  2222. begin
  2223. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2224. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2225. end
  2226. else
  2227. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2228. end;
  2229. function TryConstMerge(var p1, p2: tai): Boolean;
  2230. var
  2231. ThisRef: TReference;
  2232. begin
  2233. Result := False;
  2234. ThisRef := taicpu(p2).oper[1]^.ref^;
  2235. { Only permit writes to the stack, since we can guarantee alignment with that }
  2236. if (ThisRef.index = NR_NO) and
  2237. (
  2238. (ThisRef.base = NR_STACK_POINTER_REG) or
  2239. (ThisRef.base = current_procinfo.framepointer)
  2240. ) then
  2241. begin
  2242. case taicpu(p).opsize of
  2243. S_B:
  2244. begin
  2245. { Word writes must be on a 2-byte boundary }
  2246. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2247. begin
  2248. { Reduce offset of second reference to see if it is sequential with the first }
  2249. Dec(ThisRef.offset, 1);
  2250. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2251. begin
  2252. { Make sure the constants aren't represented as a
  2253. negative number, as these won't merge properly }
  2254. taicpu(p1).opsize := S_W;
  2255. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2256. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2257. RemoveInstruction(p2);
  2258. Result := True;
  2259. end;
  2260. end;
  2261. end;
  2262. S_W:
  2263. begin
  2264. { Longword writes must be on a 4-byte boundary }
  2265. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2266. begin
  2267. { Reduce offset of second reference to see if it is sequential with the first }
  2268. Dec(ThisRef.offset, 2);
  2269. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2270. begin
  2271. { Make sure the constants aren't represented as a
  2272. negative number, as these won't merge properly }
  2273. taicpu(p1).opsize := S_L;
  2274. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2275. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2276. RemoveInstruction(p2);
  2277. Result := True;
  2278. end;
  2279. end;
  2280. end;
  2281. {$ifdef x86_64}
  2282. S_L:
  2283. begin
  2284. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2285. see if the constants can be encoded this way. }
  2286. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2287. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2288. { Quadword writes must be on an 8-byte boundary }
  2289. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2290. begin
  2291. { Reduce offset of second reference to see if it is sequential with the first }
  2292. Dec(ThisRef.offset, 4);
  2293. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2294. begin
  2295. { Make sure the constants aren't represented as a
  2296. negative number, as these won't merge properly }
  2297. taicpu(p1).opsize := S_Q;
  2298. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2299. taicpu(p1).oper[0]^.val := NewConst;
  2300. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2301. RemoveInstruction(p2);
  2302. Result := True;
  2303. end;
  2304. end;
  2305. end;
  2306. {$endif x86_64}
  2307. else
  2308. ;
  2309. end;
  2310. end;
  2311. end;
  2312. var
  2313. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2314. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2315. NewSize: topsize;
  2316. CurrentReg, ActiveReg: TRegister;
  2317. SourceRef, TargetRef: TReference;
  2318. MovAligned, MovUnaligned: TAsmOp;
  2319. ThisRef: TReference;
  2320. begin
  2321. Result:=false;
  2322. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2323. { remove mov reg1,reg1? }
  2324. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2325. then
  2326. begin
  2327. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2328. { take care of the register (de)allocs following p }
  2329. RemoveCurrentP(p, hp1);
  2330. Result:=true;
  2331. exit;
  2332. end;
  2333. { All the next optimisations require a next instruction }
  2334. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2335. Exit;
  2336. { Look for:
  2337. mov %reg1,%reg2
  2338. ??? %reg2,r/m
  2339. Change to:
  2340. mov %reg1,%reg2
  2341. ??? %reg1,r/m
  2342. }
  2343. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2344. begin
  2345. CurrentReg := taicpu(p).oper[1]^.reg;
  2346. if RegReadByInstruction(CurrentReg, hp1) and
  2347. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2348. begin
  2349. { A change has occurred, just not in p }
  2350. Result := True;
  2351. TransferUsedRegs(TmpUsedRegs);
  2352. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2353. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2354. { Just in case something didn't get modified (e.g. an
  2355. implicit register) }
  2356. not RegReadByInstruction(CurrentReg, hp1) then
  2357. begin
  2358. { We can remove the original MOV }
  2359. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2360. RemoveCurrentp(p, hp1);
  2361. { UsedRegs got updated by RemoveCurrentp }
  2362. Result := True;
  2363. Exit;
  2364. end;
  2365. { If we know a MOV instruction has become a null operation, we might as well
  2366. get rid of it now to save time. }
  2367. if (taicpu(hp1).opcode = A_MOV) and
  2368. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2369. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2370. { Just being a register is enough to confirm it's a null operation }
  2371. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2372. begin
  2373. Result := True;
  2374. { Speed-up to reduce a pipeline stall... if we had something like...
  2375. movl %eax,%edx
  2376. movw %dx,%ax
  2377. ... the second instruction would change to movw %ax,%ax, but
  2378. given that it is now %ax that's active rather than %eax,
  2379. penalties might occur due to a partial register write, so instead,
  2380. change it to a MOVZX instruction when optimising for speed.
  2381. }
  2382. if not (cs_opt_size in current_settings.optimizerswitches) and
  2383. IsMOVZXAcceptable and
  2384. (taicpu(hp1).opsize < taicpu(p).opsize)
  2385. {$ifdef x86_64}
  2386. { operations already implicitly set the upper 64 bits to zero }
  2387. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2388. {$endif x86_64}
  2389. then
  2390. begin
  2391. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2392. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2393. case taicpu(p).opsize of
  2394. S_W:
  2395. if taicpu(hp1).opsize = S_B then
  2396. taicpu(hp1).opsize := S_BL
  2397. else
  2398. InternalError(2020012911);
  2399. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2400. case taicpu(hp1).opsize of
  2401. S_B:
  2402. taicpu(hp1).opsize := S_BL;
  2403. S_W:
  2404. taicpu(hp1).opsize := S_WL;
  2405. else
  2406. InternalError(2020012912);
  2407. end;
  2408. else
  2409. InternalError(2020012910);
  2410. end;
  2411. taicpu(hp1).opcode := A_MOVZX;
  2412. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2413. end
  2414. else
  2415. begin
  2416. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2417. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2418. RemoveInstruction(hp1);
  2419. { The instruction after what was hp1 is now the immediate next instruction,
  2420. so we can continue to make optimisations if it's present }
  2421. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2422. Exit;
  2423. hp1 := hp2;
  2424. end;
  2425. end;
  2426. end;
  2427. end;
  2428. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2429. overwrites the original destination register. e.g.
  2430. movl ###,%reg2d
  2431. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2432. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2433. }
  2434. if (taicpu(p).oper[1]^.typ = top_reg) and
  2435. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2436. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2437. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2438. begin
  2439. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2440. begin
  2441. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2442. case taicpu(p).oper[0]^.typ of
  2443. top_const:
  2444. { We have something like:
  2445. movb $x, %regb
  2446. movzbl %regb,%regd
  2447. Change to:
  2448. movl $x, %regd
  2449. }
  2450. begin
  2451. case taicpu(hp1).opsize of
  2452. S_BW:
  2453. begin
  2454. convert_mov_value(A_MOVSX, $FF);
  2455. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2456. taicpu(p).opsize := S_W;
  2457. end;
  2458. S_BL:
  2459. begin
  2460. convert_mov_value(A_MOVSX, $FF);
  2461. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2462. taicpu(p).opsize := S_L;
  2463. end;
  2464. S_WL:
  2465. begin
  2466. convert_mov_value(A_MOVSX, $FFFF);
  2467. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2468. taicpu(p).opsize := S_L;
  2469. end;
  2470. {$ifdef x86_64}
  2471. S_BQ:
  2472. begin
  2473. convert_mov_value(A_MOVSX, $FF);
  2474. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2475. taicpu(p).opsize := S_Q;
  2476. end;
  2477. S_WQ:
  2478. begin
  2479. convert_mov_value(A_MOVSX, $FFFF);
  2480. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2481. taicpu(p).opsize := S_Q;
  2482. end;
  2483. S_LQ:
  2484. begin
  2485. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2486. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2487. taicpu(p).opsize := S_Q;
  2488. end;
  2489. {$endif x86_64}
  2490. else
  2491. { If hp1 was a MOV instruction, it should have been
  2492. optimised already }
  2493. InternalError(2020021001);
  2494. end;
  2495. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2496. RemoveInstruction(hp1);
  2497. Result := True;
  2498. Exit;
  2499. end;
  2500. top_ref:
  2501. begin
  2502. { We have something like:
  2503. movb mem, %regb
  2504. movzbl %regb,%regd
  2505. Change to:
  2506. movzbl mem, %regd
  2507. }
  2508. ThisRef := taicpu(p).oper[0]^.ref^;
  2509. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2510. begin
  2511. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2512. taicpu(hp1).loadref(0, ThisRef);
  2513. { Make sure any registers in the references are properly tracked }
  2514. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2515. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2516. if (ThisRef.index <> NR_NO) then
  2517. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2518. RemoveCurrentP(p, hp1);
  2519. Result := True;
  2520. Exit;
  2521. end;
  2522. end;
  2523. else
  2524. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2525. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2526. Exit;
  2527. end;
  2528. end
  2529. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2530. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2531. optimised }
  2532. else
  2533. begin
  2534. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2535. RemoveCurrentP(p, hp1);
  2536. Result := True;
  2537. Exit;
  2538. end;
  2539. end;
  2540. if (taicpu(hp1).opcode = A_AND) and
  2541. (taicpu(p).oper[1]^.typ = top_reg) and
  2542. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2543. begin
  2544. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2545. begin
  2546. case taicpu(p).opsize of
  2547. S_L:
  2548. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2549. begin
  2550. { Optimize out:
  2551. mov x, %reg
  2552. and ffffffffh, %reg
  2553. }
  2554. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2555. RemoveInstruction(hp1);
  2556. Result:=true;
  2557. exit;
  2558. end;
  2559. S_Q: { TODO: Confirm if this is even possible }
  2560. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2561. begin
  2562. { Optimize out:
  2563. mov x, %reg
  2564. and ffffffffffffffffh, %reg
  2565. }
  2566. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2567. RemoveInstruction(hp1);
  2568. Result:=true;
  2569. exit;
  2570. end;
  2571. else
  2572. ;
  2573. end;
  2574. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2575. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2576. GetNextInstruction(hp1,hp2) and
  2577. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2578. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2579. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2580. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2581. GetNextInstruction(hp2,hp3) and
  2582. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2583. (taicpu(hp3).condition in [C_E,C_NE]) then
  2584. begin
  2585. TransferUsedRegs(TmpUsedRegs);
  2586. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2587. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2588. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2589. begin
  2590. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2591. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2592. taicpu(hp1).opcode:=A_TEST;
  2593. RemoveInstruction(hp2);
  2594. RemoveCurrentP(p, hp1);
  2595. Result:=true;
  2596. exit;
  2597. end;
  2598. end;
  2599. end
  2600. else if IsMOVZXAcceptable and
  2601. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2602. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2603. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2604. then
  2605. begin
  2606. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2607. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2608. case taicpu(p).opsize of
  2609. S_B:
  2610. if (taicpu(hp1).oper[0]^.val = $ff) then
  2611. begin
  2612. { Convert:
  2613. movb x, %regl movb x, %regl
  2614. andw ffh, %regw andl ffh, %regd
  2615. To:
  2616. movzbw x, %regd movzbl x, %regd
  2617. (Identical registers, just different sizes)
  2618. }
  2619. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2620. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2621. case taicpu(hp1).opsize of
  2622. S_W: NewSize := S_BW;
  2623. S_L: NewSize := S_BL;
  2624. {$ifdef x86_64}
  2625. S_Q: NewSize := S_BQ;
  2626. {$endif x86_64}
  2627. else
  2628. InternalError(2018011510);
  2629. end;
  2630. end
  2631. else
  2632. NewSize := S_NO;
  2633. S_W:
  2634. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2635. begin
  2636. { Convert:
  2637. movw x, %regw
  2638. andl ffffh, %regd
  2639. To:
  2640. movzwl x, %regd
  2641. (Identical registers, just different sizes)
  2642. }
  2643. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2644. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2645. case taicpu(hp1).opsize of
  2646. S_L: NewSize := S_WL;
  2647. {$ifdef x86_64}
  2648. S_Q: NewSize := S_WQ;
  2649. {$endif x86_64}
  2650. else
  2651. InternalError(2018011511);
  2652. end;
  2653. end
  2654. else
  2655. NewSize := S_NO;
  2656. else
  2657. NewSize := S_NO;
  2658. end;
  2659. if NewSize <> S_NO then
  2660. begin
  2661. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2662. { The actual optimization }
  2663. taicpu(p).opcode := A_MOVZX;
  2664. taicpu(p).changeopsize(NewSize);
  2665. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2666. { Safeguard if "and" is followed by a conditional command }
  2667. TransferUsedRegs(TmpUsedRegs);
  2668. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2669. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2670. begin
  2671. { At this point, the "and" command is effectively equivalent to
  2672. "test %reg,%reg". This will be handled separately by the
  2673. Peephole Optimizer. [Kit] }
  2674. DebugMsg(SPeepholeOptimization + PreMessage +
  2675. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2676. end
  2677. else
  2678. begin
  2679. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2680. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2681. RemoveInstruction(hp1);
  2682. end;
  2683. Result := True;
  2684. Exit;
  2685. end;
  2686. end;
  2687. end;
  2688. if (taicpu(hp1).opcode = A_OR) and
  2689. (taicpu(p).oper[1]^.typ = top_reg) and
  2690. MatchOperand(taicpu(p).oper[0]^, 0) and
  2691. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2692. begin
  2693. { mov 0, %reg
  2694. or ###,%reg
  2695. Change to (only if the flags are not used):
  2696. mov ###,%reg
  2697. }
  2698. TransferUsedRegs(TmpUsedRegs);
  2699. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2700. DoOptimisation := True;
  2701. { Even if the flags are used, we might be able to do the optimisation
  2702. if the conditions are predictable }
  2703. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2704. begin
  2705. { Only perform if ### = %reg (the same register) or equal to 0,
  2706. so %reg is guaranteed to still have a value of zero }
  2707. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2708. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2709. begin
  2710. hp2 := hp1;
  2711. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2712. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2713. GetNextInstruction(hp2, hp3) do
  2714. begin
  2715. { Don't continue modifying if the flags state is getting changed }
  2716. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2717. Break;
  2718. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2719. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2720. begin
  2721. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2722. begin
  2723. { Condition is always true }
  2724. case taicpu(hp3).opcode of
  2725. A_Jcc:
  2726. begin
  2727. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2728. { Check for jump shortcuts before we destroy the condition }
  2729. DoJumpOptimizations(hp3, TempBool);
  2730. MakeUnconditional(taicpu(hp3));
  2731. Result := True;
  2732. end;
  2733. A_CMOVcc:
  2734. begin
  2735. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2736. taicpu(hp3).opcode := A_MOV;
  2737. taicpu(hp3).condition := C_None;
  2738. Result := True;
  2739. end;
  2740. A_SETcc:
  2741. begin
  2742. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2743. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2744. taicpu(hp3).opcode := A_MOV;
  2745. taicpu(hp3).ops := 2;
  2746. taicpu(hp3).condition := C_None;
  2747. taicpu(hp3).opsize := S_B;
  2748. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2749. taicpu(hp3).loadconst(0, 1);
  2750. Result := True;
  2751. end;
  2752. else
  2753. InternalError(2021090701);
  2754. end;
  2755. end
  2756. 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
  2757. begin
  2758. { Condition is always false }
  2759. case taicpu(hp3).opcode of
  2760. A_Jcc:
  2761. begin
  2762. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2763. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2764. RemoveInstruction(hp3);
  2765. Result := True;
  2766. { Since hp3 was deleted, hp2 must not be updated }
  2767. Continue;
  2768. end;
  2769. A_CMOVcc:
  2770. begin
  2771. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2772. RemoveInstruction(hp3);
  2773. Result := True;
  2774. { Since hp3 was deleted, hp2 must not be updated }
  2775. Continue;
  2776. end;
  2777. A_SETcc:
  2778. begin
  2779. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2780. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2781. taicpu(hp3).opcode := A_MOV;
  2782. taicpu(hp3).ops := 2;
  2783. taicpu(hp3).condition := C_None;
  2784. taicpu(hp3).opsize := S_B;
  2785. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2786. taicpu(hp3).loadconst(0, 0);
  2787. Result := True;
  2788. end;
  2789. else
  2790. InternalError(2021090702);
  2791. end;
  2792. end
  2793. else
  2794. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2795. DoOptimisation := False;
  2796. end;
  2797. hp2 := hp3;
  2798. end;
  2799. { Flags are still in use - don't optimise }
  2800. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2801. DoOptimisation := False;
  2802. end
  2803. else
  2804. DoOptimisation := False;
  2805. end;
  2806. if DoOptimisation then
  2807. begin
  2808. {$ifdef x86_64}
  2809. { OR only supports 32-bit sign-extended constants for 64-bit
  2810. instructions, so compensate for this if the constant is
  2811. encoded as a value greater than or equal to 2^31 }
  2812. if (taicpu(hp1).opsize = S_Q) and
  2813. (taicpu(hp1).oper[0]^.typ = top_const) and
  2814. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2815. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2816. {$endif x86_64}
  2817. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2818. taicpu(hp1).opcode := A_MOV;
  2819. RemoveCurrentP(p, hp1);
  2820. Result := True;
  2821. Exit;
  2822. end;
  2823. end;
  2824. { Next instruction is also a MOV ? }
  2825. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2826. begin
  2827. if MatchOpType(taicpu(p), top_const, top_ref) and
  2828. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2829. TryConstMerge(p, hp1) then
  2830. begin
  2831. Result := True;
  2832. { In case we have four byte writes in a row, check for 2 more
  2833. right now so we don't have to wait for another iteration of
  2834. pass 1
  2835. }
  2836. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  2837. case taicpu(p).opsize of
  2838. S_W:
  2839. begin
  2840. if GetNextInstruction(p, hp1) and
  2841. MatchInstruction(hp1, A_MOV, [S_B]) and
  2842. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2843. GetNextInstruction(hp1, hp2) and
  2844. MatchInstruction(hp2, A_MOV, [S_B]) and
  2845. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2846. { Try to merge the two bytes }
  2847. TryConstMerge(hp1, hp2) then
  2848. { Now try to merge the two words (hp2 will get deleted) }
  2849. TryConstMerge(p, hp1);
  2850. end;
  2851. S_L:
  2852. begin
  2853. { Though this only really benefits x86_64 and not i386, it
  2854. gets a potential optimisation done faster and hence
  2855. reduces the number of times OptPass1MOV is entered }
  2856. if GetNextInstruction(p, hp1) and
  2857. MatchInstruction(hp1, A_MOV, [S_W]) and
  2858. MatchOpType(taicpu(hp1), top_const, top_ref) and
  2859. GetNextInstruction(hp1, hp2) and
  2860. MatchInstruction(hp2, A_MOV, [S_W]) and
  2861. MatchOpType(taicpu(hp2), top_const, top_ref) and
  2862. { Try to merge the two words }
  2863. TryConstMerge(hp1, hp2) then
  2864. { This will always fail on i386, so don't bother
  2865. calling it unless we're doing x86_64 }
  2866. {$ifdef x86_64}
  2867. { Now try to merge the two longwords (hp2 will get deleted) }
  2868. TryConstMerge(p, hp1)
  2869. {$endif x86_64}
  2870. ;
  2871. end;
  2872. else
  2873. ;
  2874. end;
  2875. Exit;
  2876. end;
  2877. if (taicpu(p).oper[1]^.typ = top_reg) and
  2878. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2879. begin
  2880. CurrentReg := taicpu(p).oper[1]^.reg;
  2881. TransferUsedRegs(TmpUsedRegs);
  2882. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2883. { we have
  2884. mov x, %treg
  2885. mov %treg, y
  2886. }
  2887. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2888. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2889. { we've got
  2890. mov x, %treg
  2891. mov %treg, y
  2892. with %treg is not used after }
  2893. case taicpu(p).oper[0]^.typ Of
  2894. { top_reg is covered by DeepMOVOpt }
  2895. top_const:
  2896. begin
  2897. { change
  2898. mov const, %treg
  2899. mov %treg, y
  2900. to
  2901. mov const, y
  2902. }
  2903. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2904. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2905. begin
  2906. if taicpu(hp1).oper[1]^.typ=top_reg then
  2907. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2908. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2909. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2910. RemoveInstruction(hp1);
  2911. Result:=true;
  2912. Exit;
  2913. end;
  2914. end;
  2915. top_ref:
  2916. case taicpu(hp1).oper[1]^.typ of
  2917. top_reg:
  2918. begin
  2919. { change
  2920. mov mem, %treg
  2921. mov %treg, %reg
  2922. to
  2923. mov mem, %reg"
  2924. }
  2925. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2926. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2927. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2928. RemoveInstruction(hp1);
  2929. Result:=true;
  2930. Exit;
  2931. end;
  2932. top_ref:
  2933. begin
  2934. {$ifdef x86_64}
  2935. { Look for the following to simplify:
  2936. mov x(mem1), %reg
  2937. mov %reg, y(mem2)
  2938. mov x+8(mem1), %reg
  2939. mov %reg, y+8(mem2)
  2940. Change to:
  2941. movdqu x(mem1), %xmmreg
  2942. movdqu %xmmreg, y(mem2)
  2943. }
  2944. SourceRef := taicpu(p).oper[0]^.ref^;
  2945. TargetRef := taicpu(hp1).oper[1]^.ref^;
  2946. if (taicpu(p).opsize = S_Q) and
  2947. GetNextInstruction(hp1, hp2) and
  2948. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  2949. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  2950. begin
  2951. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  2952. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2953. Inc(SourceRef.offset, 8);
  2954. if UseAVX then
  2955. begin
  2956. MovAligned := A_VMOVDQA;
  2957. MovUnaligned := A_VMOVDQU;
  2958. end
  2959. else
  2960. begin
  2961. MovAligned := A_MOVDQA;
  2962. MovUnaligned := A_MOVDQU;
  2963. end;
  2964. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  2965. begin
  2966. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  2967. Inc(TargetRef.offset, 8);
  2968. if GetNextInstruction(hp2, hp3) and
  2969. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  2970. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  2971. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  2972. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  2973. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  2974. begin
  2975. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  2976. if CurrentReg <> NR_NO then
  2977. begin
  2978. { Remember that the offsets are 8 ahead }
  2979. if ((SourceRef.offset mod 16) = 8) and
  2980. (
  2981. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2982. (SourceRef.base = current_procinfo.framepointer) or
  2983. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  2984. ) then
  2985. taicpu(p).opcode := MovAligned
  2986. else
  2987. taicpu(p).opcode := MovUnaligned;
  2988. taicpu(p).opsize := S_XMM;
  2989. taicpu(p).oper[1]^.reg := CurrentReg;
  2990. if ((TargetRef.offset mod 16) = 8) and
  2991. (
  2992. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  2993. (TargetRef.base = current_procinfo.framepointer) or
  2994. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  2995. ) then
  2996. taicpu(hp1).opcode := MovAligned
  2997. else
  2998. taicpu(hp1).opcode := MovUnaligned;
  2999. taicpu(hp1).opsize := S_XMM;
  3000. taicpu(hp1).oper[0]^.reg := CurrentReg;
  3001. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3002. RemoveInstruction(hp2);
  3003. RemoveInstruction(hp3);
  3004. Result := True;
  3005. Exit;
  3006. end;
  3007. end;
  3008. end
  3009. else
  3010. begin
  3011. { See if the next references are 8 less rather than 8 greater }
  3012. Dec(SourceRef.offset, 16); { -8 the other way }
  3013. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3014. begin
  3015. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3016. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3017. if GetNextInstruction(hp2, hp3) and
  3018. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3019. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3020. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3021. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3022. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3023. begin
  3024. CurrentReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3025. if CurrentReg <> NR_NO then
  3026. begin
  3027. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3028. if ((SourceRef.offset mod 16) = 0) and
  3029. (
  3030. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3031. (SourceRef.base = current_procinfo.framepointer) or
  3032. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3033. ) then
  3034. taicpu(hp2).opcode := MovAligned
  3035. else
  3036. taicpu(hp2).opcode := MovUnaligned;
  3037. taicpu(hp2).opsize := S_XMM;
  3038. taicpu(hp2).oper[1]^.reg := CurrentReg;
  3039. if ((TargetRef.offset mod 16) = 0) and
  3040. (
  3041. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3042. (TargetRef.base = current_procinfo.framepointer) or
  3043. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3044. ) then
  3045. taicpu(hp3).opcode := MovAligned
  3046. else
  3047. taicpu(hp3).opcode := MovUnaligned;
  3048. taicpu(hp3).opsize := S_XMM;
  3049. taicpu(hp3).oper[0]^.reg := CurrentReg;
  3050. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3051. RemoveInstruction(hp1);
  3052. RemoveCurrentP(p, hp2);
  3053. Result := True;
  3054. Exit;
  3055. end;
  3056. end;
  3057. end;
  3058. end;
  3059. end;
  3060. {$endif x86_64}
  3061. end;
  3062. else
  3063. { The write target should be a reg or a ref }
  3064. InternalError(2021091601);
  3065. end;
  3066. else
  3067. ;
  3068. end
  3069. else
  3070. { %treg is used afterwards, but all eventualities
  3071. other than the first MOV instruction being a constant
  3072. are covered by DeepMOVOpt, so only check for that }
  3073. if (taicpu(p).oper[0]^.typ = top_const) and
  3074. (
  3075. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3076. not (cs_opt_size in current_settings.optimizerswitches) or
  3077. (taicpu(hp1).opsize = S_B)
  3078. ) and
  3079. (
  3080. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3081. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3082. ) then
  3083. begin
  3084. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3085. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3086. end;
  3087. end;
  3088. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3089. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3090. { mov reg1, mem1 or mov mem1, reg1
  3091. mov mem2, reg2 mov reg2, mem2}
  3092. begin
  3093. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3094. { mov reg1, mem1 or mov mem1, reg1
  3095. mov mem2, reg1 mov reg2, mem1}
  3096. begin
  3097. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3098. { Removes the second statement from
  3099. mov reg1, mem1/reg2
  3100. mov mem1/reg2, reg1 }
  3101. begin
  3102. if taicpu(p).oper[0]^.typ=top_reg then
  3103. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3104. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3105. RemoveInstruction(hp1);
  3106. Result:=true;
  3107. exit;
  3108. end
  3109. else
  3110. begin
  3111. TransferUsedRegs(TmpUsedRegs);
  3112. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3113. if (taicpu(p).oper[1]^.typ = top_ref) and
  3114. { mov reg1, mem1
  3115. mov mem2, reg1 }
  3116. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3117. GetNextInstruction(hp1, hp2) and
  3118. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3119. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3120. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3121. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3122. { change to
  3123. mov reg1, mem1 mov reg1, mem1
  3124. mov mem2, reg1 cmp reg1, mem2
  3125. cmp mem1, reg1
  3126. }
  3127. begin
  3128. RemoveInstruction(hp2);
  3129. taicpu(hp1).opcode := A_CMP;
  3130. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3131. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3132. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3133. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3134. end;
  3135. end;
  3136. end
  3137. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3138. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3139. begin
  3140. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3141. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3142. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3143. end
  3144. else
  3145. begin
  3146. TransferUsedRegs(TmpUsedRegs);
  3147. if GetNextInstruction(hp1, hp2) and
  3148. MatchOpType(taicpu(p),top_ref,top_reg) and
  3149. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3150. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3151. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3152. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3153. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3154. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3155. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3156. { mov mem1, %reg1
  3157. mov %reg1, mem2
  3158. mov mem2, reg2
  3159. to:
  3160. mov mem1, reg2
  3161. mov reg2, mem2}
  3162. begin
  3163. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3164. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3165. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3166. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3167. RemoveInstruction(hp2);
  3168. Result := True;
  3169. end
  3170. {$ifdef i386}
  3171. { this is enabled for i386 only, as the rules to create the reg sets below
  3172. are too complicated for x86-64, so this makes this code too error prone
  3173. on x86-64
  3174. }
  3175. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3176. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3177. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3178. { mov mem1, reg1 mov mem1, reg1
  3179. mov reg1, mem2 mov reg1, mem2
  3180. mov mem2, reg2 mov mem2, reg1
  3181. to: to:
  3182. mov mem1, reg1 mov mem1, reg1
  3183. mov mem1, reg2 mov reg1, mem2
  3184. mov reg1, mem2
  3185. or (if mem1 depends on reg1
  3186. and/or if mem2 depends on reg2)
  3187. to:
  3188. mov mem1, reg1
  3189. mov reg1, mem2
  3190. mov reg1, reg2
  3191. }
  3192. begin
  3193. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3194. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3195. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3196. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3197. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3198. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3199. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3200. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3201. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3202. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3203. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3204. end
  3205. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3206. begin
  3207. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3208. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3209. end
  3210. else
  3211. begin
  3212. RemoveInstruction(hp2);
  3213. end
  3214. {$endif i386}
  3215. ;
  3216. end;
  3217. end
  3218. { movl [mem1],reg1
  3219. movl [mem1],reg2
  3220. to
  3221. movl [mem1],reg1
  3222. movl reg1,reg2
  3223. }
  3224. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3225. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3226. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3227. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3228. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3229. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3230. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3231. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3232. begin
  3233. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3234. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3235. end;
  3236. { movl const1,[mem1]
  3237. movl [mem1],reg1
  3238. to
  3239. movl const1,reg1
  3240. movl reg1,[mem1]
  3241. }
  3242. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3243. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3244. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3245. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3246. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3247. begin
  3248. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3249. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3250. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3251. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3252. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3253. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3254. Result:=true;
  3255. exit;
  3256. end;
  3257. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3258. { Change:
  3259. movl %reg1,%reg2
  3260. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3261. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3262. To:
  3263. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3264. movl x(%reg1),%reg1
  3265. movl %reg1,%regX
  3266. }
  3267. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3268. begin
  3269. CurrentReg := taicpu(p).oper[0]^.reg;
  3270. ActiveReg := taicpu(p).oper[1]^.reg;
  3271. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3272. (taicpu(hp1).oper[1]^.reg = CurrentReg) and
  3273. RegInRef(CurrentReg, taicpu(hp1).oper[0]^.ref^) and
  3274. GetNextInstruction(hp1, hp2) and
  3275. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3276. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3277. begin
  3278. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3279. if RegInRef(ActiveReg, SourceRef) and
  3280. { If %reg1 also appears in the second reference, then it will
  3281. not refer to the same memory block as the first reference }
  3282. not RegInRef(CurrentReg, SourceRef) then
  3283. begin
  3284. { Check to see if the references match if %reg2 is changed to %reg1 }
  3285. if SourceRef.base = ActiveReg then
  3286. SourceRef.base := CurrentReg;
  3287. if SourceRef.index = ActiveReg then
  3288. SourceRef.index := CurrentReg;
  3289. { RefsEqual also checks to ensure both references are non-volatile }
  3290. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3291. begin
  3292. taicpu(hp2).loadreg(0, CurrentReg);
  3293. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3294. Result := True;
  3295. if taicpu(hp2).oper[1]^.reg = ActiveReg then
  3296. begin
  3297. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3298. RemoveCurrentP(p, hp1);
  3299. Exit;
  3300. end
  3301. else
  3302. begin
  3303. { Check to see if %reg2 is no longer in use }
  3304. TransferUsedRegs(TmpUsedRegs);
  3305. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3306. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3307. if not RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs) then
  3308. begin
  3309. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3310. RemoveCurrentP(p, hp1);
  3311. Exit;
  3312. end;
  3313. end;
  3314. { If we reach this point, p and hp1 weren't actually modified,
  3315. so we can do a bit more work on this pass }
  3316. end;
  3317. end;
  3318. end;
  3319. end;
  3320. end;
  3321. { search further than the next instruction for a mov (as long as it's not a jump) }
  3322. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3323. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3324. (taicpu(p).oper[1]^.typ = top_reg) and
  3325. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3326. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3327. begin
  3328. { we work with hp2 here, so hp1 can be still used later on when
  3329. checking for GetNextInstruction_p }
  3330. hp3 := hp1;
  3331. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3332. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3333. { Saves on a large number of dereferences }
  3334. ActiveReg := taicpu(p).oper[1]^.reg;
  3335. TransferUsedRegs(TmpUsedRegs);
  3336. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3337. while GetNextInstructionUsingRegCond(hp3,hp2,ActiveReg,CrossJump) and
  3338. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3339. (hp2.typ=ait_instruction) do
  3340. begin
  3341. case taicpu(hp2).opcode of
  3342. A_POP:
  3343. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) then
  3344. begin
  3345. if not CrossJump and
  3346. not RegUsedBetween(ActiveReg, p, hp2) then
  3347. begin
  3348. { We can remove the original MOV since the register
  3349. wasn't used between it and its popping from the stack }
  3350. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3351. RemoveCurrentp(p, hp1);
  3352. Result := True;
  3353. Exit;
  3354. end;
  3355. { Can't go any further }
  3356. Break;
  3357. end;
  3358. A_MOV:
  3359. if MatchOperand(taicpu(hp2).oper[0]^,ActiveReg) and
  3360. ((taicpu(p).oper[0]^.typ=top_const) or
  3361. ((taicpu(p).oper[0]^.typ=top_reg) and
  3362. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3363. )
  3364. ) then
  3365. begin
  3366. { we have
  3367. mov x, %treg
  3368. mov %treg, y
  3369. }
  3370. { We don't need to call UpdateUsedRegs for every instruction between
  3371. p and hp2 because the register we're concerned about will not
  3372. become deallocated (otherwise GetNextInstructionUsingReg would
  3373. have stopped at an earlier instruction). [Kit] }
  3374. TempRegUsed :=
  3375. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3376. RegReadByInstruction(ActiveReg, hp3) or
  3377. RegUsedAfterInstruction(ActiveReg, hp2, TmpUsedRegs);
  3378. case taicpu(p).oper[0]^.typ Of
  3379. top_reg:
  3380. begin
  3381. { change
  3382. mov %reg, %treg
  3383. mov %treg, y
  3384. to
  3385. mov %reg, y
  3386. }
  3387. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3388. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3389. if MatchOperand(taicpu(hp2).oper[1]^, CurrentReg) then
  3390. begin
  3391. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3392. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3393. if TempRegUsed then
  3394. begin
  3395. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3396. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3397. { Set the start of the next GetNextInstructionUsingRegCond search
  3398. to start at the entry right before hp2 (which is about to be removed) }
  3399. hp3 := tai(hp2.Previous);
  3400. RemoveInstruction(hp2);
  3401. { See if there's more we can optimise }
  3402. Continue;
  3403. end
  3404. else
  3405. begin
  3406. RemoveInstruction(hp2);
  3407. { We can remove the original MOV too }
  3408. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3409. RemoveCurrentP(p, hp1);
  3410. Result:=true;
  3411. Exit;
  3412. end;
  3413. end
  3414. else
  3415. begin
  3416. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  3417. taicpu(hp2).loadReg(0, CurrentReg);
  3418. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3419. { Check to see if the register also appears in the reference }
  3420. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3421. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, ActiveReg, CurrentReg);
  3422. { Don't remove the first instruction if the temporary register is in use }
  3423. if not TempRegUsed and
  3424. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3425. not RegInOp(ActiveReg, taicpu(hp2).oper[1]^) then
  3426. begin
  3427. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3428. RemoveCurrentP(p, hp1);
  3429. Result:=true;
  3430. Exit;
  3431. end;
  3432. { No need to set Result to True here. If there's another instruction later
  3433. on that can be optimised, it will be detected when the main Pass 1 loop
  3434. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3435. end;
  3436. end;
  3437. top_const:
  3438. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3439. begin
  3440. { change
  3441. mov const, %treg
  3442. mov %treg, y
  3443. to
  3444. mov const, y
  3445. }
  3446. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3447. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3448. begin
  3449. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3450. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3451. if TempRegUsed then
  3452. begin
  3453. { Don't remove the first instruction if the temporary register is in use }
  3454. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3455. { No need to set Result to True. If there's another instruction later on
  3456. that can be optimised, it will be detected when the main Pass 1 loop
  3457. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3458. end
  3459. else
  3460. begin
  3461. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3462. RemoveCurrentP(p, hp1);
  3463. Result:=true;
  3464. Exit;
  3465. end;
  3466. end;
  3467. end;
  3468. else
  3469. Internalerror(2019103001);
  3470. end;
  3471. end
  3472. else
  3473. if MatchOperand(taicpu(hp2).oper[1]^, ActiveReg) then
  3474. begin
  3475. if not CrossJump and
  3476. not RegUsedBetween(ActiveReg, p, hp2) and
  3477. not RegReadByInstruction(ActiveReg, hp2) then
  3478. begin
  3479. { Register is not used before it is overwritten }
  3480. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3481. RemoveCurrentp(p, hp1);
  3482. Result := True;
  3483. Exit;
  3484. end;
  3485. if (taicpu(p).oper[0]^.typ = top_const) and
  3486. (taicpu(hp2).oper[0]^.typ = top_const) then
  3487. begin
  3488. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3489. begin
  3490. { Same value - register hasn't changed }
  3491. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3492. RemoveInstruction(hp2);
  3493. Result := True;
  3494. { See if there's more we can optimise }
  3495. Continue;
  3496. end;
  3497. end;
  3498. end;
  3499. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3500. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3501. MatchOperand(taicpu(hp2).oper[0]^, ActiveReg) and
  3502. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, ActiveReg) then
  3503. begin
  3504. {
  3505. Change from:
  3506. mov ###, %reg
  3507. ...
  3508. movs/z %reg,%reg (Same register, just different sizes)
  3509. To:
  3510. movs/z ###, %reg (Longer version)
  3511. ...
  3512. (remove)
  3513. }
  3514. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3515. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3516. { Keep the first instruction as mov if ### is a constant }
  3517. if taicpu(p).oper[0]^.typ = top_const then
  3518. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3519. else
  3520. begin
  3521. taicpu(p).opcode := taicpu(hp2).opcode;
  3522. taicpu(p).opsize := taicpu(hp2).opsize;
  3523. end;
  3524. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3525. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3526. RemoveInstruction(hp2);
  3527. Result := True;
  3528. Exit;
  3529. end;
  3530. else
  3531. { Move down to the MatchOpType if-block below };
  3532. end;
  3533. { Also catches MOV/S/Z instructions that aren't modified }
  3534. if taicpu(p).oper[0]^.typ = top_reg then
  3535. begin
  3536. CurrentReg := taicpu(p).oper[0]^.reg;
  3537. if
  3538. not RegModifiedByInstruction(CurrentReg, hp3) and
  3539. not RegModifiedBetween(CurrentReg, hp3, hp2) and
  3540. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3541. begin
  3542. Result := True;
  3543. { Just in case something didn't get modified (e.g. an
  3544. implicit register). Also, if it does read from this
  3545. register, then there's no longer an advantage to
  3546. changing the register on subsequent instructions.}
  3547. if not RegReadByInstruction(ActiveReg, hp2) then
  3548. begin
  3549. { If a conditional jump was crossed, do not delete
  3550. the original MOV no matter what }
  3551. if not CrossJump and
  3552. { RegEndOfLife returns True if the register is
  3553. deallocated before the next instruction or has
  3554. been loaded with a new value }
  3555. RegEndOfLife(ActiveReg, taicpu(hp2)) then
  3556. begin
  3557. { We can remove the original MOV }
  3558. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3559. RemoveCurrentp(p, hp1);
  3560. Exit;
  3561. end;
  3562. if not RegModifiedByInstruction(ActiveReg, hp2) then
  3563. begin
  3564. { See if there's more we can optimise }
  3565. hp3 := hp2;
  3566. Continue;
  3567. end;
  3568. end;
  3569. end;
  3570. end;
  3571. { Break out of the while loop under normal circumstances }
  3572. Break;
  3573. end;
  3574. end;
  3575. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3576. (taicpu(p).oper[1]^.typ = top_reg) and
  3577. (taicpu(p).opsize = S_L) and
  3578. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3579. (taicpu(hp2).opcode = A_AND) and
  3580. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3581. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3582. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3583. ) then
  3584. begin
  3585. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  3586. begin
  3587. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  3588. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  3589. begin
  3590. { Optimize out:
  3591. mov x, %reg
  3592. and ffffffffh, %reg
  3593. }
  3594. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  3595. RemoveInstruction(hp2);
  3596. Result:=true;
  3597. exit;
  3598. end;
  3599. end;
  3600. end;
  3601. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  3602. x >= RetOffset) as it doesn't do anything (it writes either to a
  3603. parameter or to the temporary storage room for the function
  3604. result)
  3605. }
  3606. if IsExitCode(hp1) and
  3607. (taicpu(p).oper[1]^.typ = top_ref) and
  3608. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3609. (
  3610. (
  3611. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3612. not (
  3613. assigned(current_procinfo.procdef.funcretsym) and
  3614. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3615. )
  3616. ) or
  3617. { Also discard writes to the stack that are below the base pointer,
  3618. as this is temporary storage rather than a function result on the
  3619. stack, say. }
  3620. (
  3621. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3622. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3623. )
  3624. ) then
  3625. begin
  3626. RemoveCurrentp(p, hp1);
  3627. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3628. RemoveLastDeallocForFuncRes(p);
  3629. Result:=true;
  3630. exit;
  3631. end;
  3632. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3633. begin
  3634. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3635. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3636. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3637. begin
  3638. { change
  3639. mov reg1, mem1
  3640. test/cmp x, mem1
  3641. to
  3642. mov reg1, mem1
  3643. test/cmp x, reg1
  3644. }
  3645. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3646. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3647. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3648. Result := True;
  3649. Exit;
  3650. end;
  3651. if DoMovCmpMemOpt(p, hp1, True) then
  3652. begin
  3653. Result := True;
  3654. Exit;
  3655. end;
  3656. end;
  3657. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3658. { If the flags register is in use, don't change the instruction to an
  3659. ADD otherwise this will scramble the flags. [Kit] }
  3660. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3661. begin
  3662. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3663. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3664. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3665. ) or
  3666. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3667. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3668. )
  3669. ) then
  3670. { mov reg1,ref
  3671. lea reg2,[reg1,reg2]
  3672. to
  3673. add reg2,ref}
  3674. begin
  3675. TransferUsedRegs(TmpUsedRegs);
  3676. { reg1 may not be used afterwards }
  3677. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3678. begin
  3679. Taicpu(hp1).opcode:=A_ADD;
  3680. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3681. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3682. RemoveCurrentp(p, hp1);
  3683. result:=true;
  3684. exit;
  3685. end;
  3686. end;
  3687. { If the LEA instruction can be converted into an arithmetic instruction,
  3688. it may be possible to then fold it in the next optimisation, otherwise
  3689. there's nothing more that can be optimised here. }
  3690. if not ConvertLEA(taicpu(hp1)) then
  3691. Exit;
  3692. end;
  3693. if (taicpu(p).oper[1]^.typ = top_reg) and
  3694. (hp1.typ = ait_instruction) and
  3695. GetNextInstruction(hp1, hp2) and
  3696. MatchInstruction(hp2,A_MOV,[]) and
  3697. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3698. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3699. (
  3700. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3701. {$ifdef x86_64}
  3702. or
  3703. (
  3704. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3705. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3706. )
  3707. {$endif x86_64}
  3708. ) then
  3709. begin
  3710. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3711. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3712. { change movsX/movzX reg/ref, reg2
  3713. add/sub/or/... reg3/$const, reg2
  3714. mov reg2 reg/ref
  3715. dealloc reg2
  3716. to
  3717. add/sub/or/... reg3/$const, reg/ref }
  3718. begin
  3719. TransferUsedRegs(TmpUsedRegs);
  3720. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3721. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3722. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3723. begin
  3724. { by example:
  3725. movswl %si,%eax movswl %si,%eax p
  3726. decl %eax addl %edx,%eax hp1
  3727. movw %ax,%si movw %ax,%si hp2
  3728. ->
  3729. movswl %si,%eax movswl %si,%eax p
  3730. decw %eax addw %edx,%eax hp1
  3731. movw %ax,%si movw %ax,%si hp2
  3732. }
  3733. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3734. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3735. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3736. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3737. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3738. {
  3739. ->
  3740. movswl %si,%eax movswl %si,%eax p
  3741. decw %si addw %dx,%si hp1
  3742. movw %ax,%si movw %ax,%si hp2
  3743. }
  3744. case taicpu(hp1).ops of
  3745. 1:
  3746. begin
  3747. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3748. if taicpu(hp1).oper[0]^.typ=top_reg then
  3749. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3750. end;
  3751. 2:
  3752. begin
  3753. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3754. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3755. (taicpu(hp1).opcode<>A_SHL) and
  3756. (taicpu(hp1).opcode<>A_SHR) and
  3757. (taicpu(hp1).opcode<>A_SAR) then
  3758. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3759. end;
  3760. else
  3761. internalerror(2008042701);
  3762. end;
  3763. {
  3764. ->
  3765. decw %si addw %dx,%si p
  3766. }
  3767. RemoveInstruction(hp2);
  3768. RemoveCurrentP(p, hp1);
  3769. Result:=True;
  3770. Exit;
  3771. end;
  3772. end;
  3773. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3774. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3775. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3776. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3777. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3778. )
  3779. {$ifdef i386}
  3780. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3781. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3782. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3783. {$endif i386}
  3784. then
  3785. { change movsX/movzX reg/ref, reg2
  3786. add/sub/or/... regX/$const, reg2
  3787. mov reg2, reg3
  3788. dealloc reg2
  3789. to
  3790. movsX/movzX reg/ref, reg3
  3791. add/sub/or/... reg3/$const, reg3
  3792. }
  3793. begin
  3794. TransferUsedRegs(TmpUsedRegs);
  3795. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3796. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3797. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3798. begin
  3799. { by example:
  3800. movswl %si,%eax movswl %si,%eax p
  3801. decl %eax addl %edx,%eax hp1
  3802. movw %ax,%si movw %ax,%si hp2
  3803. ->
  3804. movswl %si,%eax movswl %si,%eax p
  3805. decw %eax addw %edx,%eax hp1
  3806. movw %ax,%si movw %ax,%si hp2
  3807. }
  3808. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3809. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3810. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3811. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3812. { limit size of constants as well to avoid assembler errors, but
  3813. check opsize to avoid overflow when left shifting the 1 }
  3814. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3815. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3816. {$ifdef x86_64}
  3817. { Be careful of, for example:
  3818. movl %reg1,%reg2
  3819. addl %reg3,%reg2
  3820. movq %reg2,%reg4
  3821. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3822. }
  3823. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3824. begin
  3825. taicpu(hp2).changeopsize(S_L);
  3826. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3827. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3828. end;
  3829. {$endif x86_64}
  3830. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3831. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3832. if taicpu(p).oper[0]^.typ=top_reg then
  3833. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3834. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3835. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3836. {
  3837. ->
  3838. movswl %si,%eax movswl %si,%eax p
  3839. decw %si addw %dx,%si hp1
  3840. movw %ax,%si movw %ax,%si hp2
  3841. }
  3842. case taicpu(hp1).ops of
  3843. 1:
  3844. begin
  3845. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3846. if taicpu(hp1).oper[0]^.typ=top_reg then
  3847. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3848. end;
  3849. 2:
  3850. begin
  3851. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3852. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3853. (taicpu(hp1).opcode<>A_SHL) and
  3854. (taicpu(hp1).opcode<>A_SHR) and
  3855. (taicpu(hp1).opcode<>A_SAR) then
  3856. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3857. end;
  3858. else
  3859. internalerror(2018111801);
  3860. end;
  3861. {
  3862. ->
  3863. decw %si addw %dx,%si p
  3864. }
  3865. RemoveInstruction(hp2);
  3866. end;
  3867. end;
  3868. end;
  3869. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3870. GetNextInstruction(hp1, hp2) and
  3871. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3872. MatchOperand(Taicpu(p).oper[0]^,0) and
  3873. (Taicpu(p).oper[1]^.typ = top_reg) and
  3874. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3875. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3876. { mov reg1,0
  3877. bts reg1,operand1 --> mov reg1,operand2
  3878. or reg1,operand2 bts reg1,operand1}
  3879. begin
  3880. Taicpu(hp2).opcode:=A_MOV;
  3881. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  3882. asml.remove(hp1);
  3883. insertllitem(hp2,hp2.next,hp1);
  3884. RemoveCurrentp(p, hp1);
  3885. Result:=true;
  3886. exit;
  3887. end;
  3888. {
  3889. mov ref,reg0
  3890. <op> reg0,reg1
  3891. dealloc reg0
  3892. to
  3893. <op> ref,reg1
  3894. }
  3895. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3896. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  3897. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3898. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  3899. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  3900. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  3901. begin
  3902. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  3903. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  3904. RemoveCurrentp(p, hp1);
  3905. Result:=true;
  3906. exit;
  3907. end;
  3908. {$ifdef x86_64}
  3909. { Convert:
  3910. movq x(ref),%reg64
  3911. shrq y,%reg64
  3912. To:
  3913. movl x+4(ref),%reg32
  3914. shrl y-32,%reg32 (Remove if y = 32)
  3915. }
  3916. if (taicpu(p).opsize = S_Q) and
  3917. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3918. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3919. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3920. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3921. (taicpu(hp1).oper[0]^.val >= 32) and
  3922. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3923. begin
  3924. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3925. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3926. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3927. { Convert to 32-bit }
  3928. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3929. taicpu(p).opsize := S_L;
  3930. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3931. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3932. if (taicpu(hp1).oper[0]^.val = 32) then
  3933. begin
  3934. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3935. RemoveInstruction(hp1);
  3936. end
  3937. else
  3938. begin
  3939. { This will potentially open up more arithmetic operations since
  3940. the peephole optimizer now has a big hint that only the lower
  3941. 32 bits are currently in use (and opcodes are smaller in size) }
  3942. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3943. taicpu(hp1).opsize := S_L;
  3944. Dec(taicpu(hp1).oper[0]^.val, 32);
  3945. DebugMsg(SPeepholeOptimization + PreMessage +
  3946. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3947. end;
  3948. Result := True;
  3949. Exit;
  3950. end;
  3951. {$endif x86_64}
  3952. { Backward optimisation. If we have:
  3953. func. %reg1,%reg2
  3954. mov %reg2,%reg3
  3955. (dealloc %reg2)
  3956. Change to:
  3957. func. %reg1,%reg3 (see comment below for what a valid func. is)
  3958. }
  3959. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3960. begin
  3961. CurrentReg := taicpu(p).oper[0]^.reg;
  3962. ActiveReg := taicpu(p).oper[1]^.reg;
  3963. TransferUsedRegs(TmpUsedRegs);
  3964. if not RegUsedAfterInstruction(CurrentReg, p, TmpUsedRegs) and
  3965. GetLastInstruction(p, hp2) and
  3966. (hp2.typ = ait_instruction) and
  3967. { Have to make sure it's an instruction that only reads from
  3968. operand 1 and only writes (not reads or modifies) from operand 2;
  3969. in essence, a one-operand pure function such as BSR or POPCNT }
  3970. (taicpu(hp2).ops = 2) and
  3971. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2]) and
  3972. (taicpu(hp2).oper[1]^.typ = top_reg) and
  3973. (taicpu(hp2).oper[1]^.reg = CurrentReg) then
  3974. begin
  3975. case taicpu(hp2).opcode of
  3976. A_FSTSW, A_FNSTSW,
  3977. A_IN, A_INS, A_OUT, A_OUTS,
  3978. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS,
  3979. { These routines have explicit operands, but they are restricted in
  3980. what they can be (e.g. IN and OUT can only read from AL, AX or
  3981. EAX. }
  3982. A_CMOVcc:
  3983. { CMOV is not valid either because then CurrentReg will depend
  3984. on an unknown value if the condition is False and hence is
  3985. not a pure write }
  3986. ;
  3987. else
  3988. begin
  3989. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  3990. taicpu(hp2).oper[1]^.reg := ActiveReg;
  3991. AllocRegBetween(ActiveReg, hp2, p, TmpUsedRegs);
  3992. RemoveCurrentp(p, hp1);
  3993. Result := True;
  3994. Exit;
  3995. end;
  3996. end;
  3997. end;
  3998. end;
  3999. end;
  4000. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4001. var
  4002. hp1 : tai;
  4003. begin
  4004. Result:=false;
  4005. if taicpu(p).ops <> 2 then
  4006. exit;
  4007. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4008. GetNextInstruction(p,hp1) then
  4009. begin
  4010. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4011. (taicpu(hp1).ops = 2) then
  4012. begin
  4013. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4014. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4015. { movXX reg1, mem1 or movXX mem1, reg1
  4016. movXX mem2, reg2 movXX reg2, mem2}
  4017. begin
  4018. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4019. { movXX reg1, mem1 or movXX mem1, reg1
  4020. movXX mem2, reg1 movXX reg2, mem1}
  4021. begin
  4022. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4023. begin
  4024. { Removes the second statement from
  4025. movXX reg1, mem1/reg2
  4026. movXX mem1/reg2, reg1
  4027. }
  4028. if taicpu(p).oper[0]^.typ=top_reg then
  4029. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4030. { Removes the second statement from
  4031. movXX mem1/reg1, reg2
  4032. movXX reg2, mem1/reg1
  4033. }
  4034. if (taicpu(p).oper[1]^.typ=top_reg) and
  4035. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4036. begin
  4037. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4038. RemoveInstruction(hp1);
  4039. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4040. Result:=true;
  4041. exit;
  4042. end
  4043. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4044. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4045. begin
  4046. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4047. RemoveInstruction(hp1);
  4048. Result:=true;
  4049. exit;
  4050. end;
  4051. end
  4052. end;
  4053. end;
  4054. end;
  4055. end;
  4056. end;
  4057. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4058. var
  4059. hp1 : tai;
  4060. begin
  4061. result:=false;
  4062. { replace
  4063. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4064. MovX %mreg2,%mreg1
  4065. dealloc %mreg2
  4066. by
  4067. <Op>X %mreg2,%mreg1
  4068. ?
  4069. }
  4070. if GetNextInstruction(p,hp1) and
  4071. { we mix single and double opperations here because we assume that the compiler
  4072. generates vmovapd only after double operations and vmovaps only after single operations }
  4073. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4074. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4075. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4076. (taicpu(p).oper[0]^.typ=top_reg) then
  4077. begin
  4078. TransferUsedRegs(TmpUsedRegs);
  4079. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4080. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4081. begin
  4082. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4083. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4084. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4085. RemoveInstruction(hp1);
  4086. result:=true;
  4087. end;
  4088. end;
  4089. end;
  4090. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4091. var
  4092. hp1, p_label, p_dist, hp1_dist: tai;
  4093. JumpLabel, JumpLabel_dist: TAsmLabel;
  4094. FirstValue, SecondValue: TCGInt;
  4095. begin
  4096. Result := False;
  4097. if (taicpu(p).oper[0]^.typ = top_const) and
  4098. (taicpu(p).oper[0]^.val <> -1) then
  4099. begin
  4100. { Convert unsigned maximum constants to -1 to aid optimisation }
  4101. case taicpu(p).opsize of
  4102. S_B:
  4103. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4104. begin
  4105. taicpu(p).oper[0]^.val := -1;
  4106. Result := True;
  4107. Exit;
  4108. end;
  4109. S_W:
  4110. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4111. begin
  4112. taicpu(p).oper[0]^.val := -1;
  4113. Result := True;
  4114. Exit;
  4115. end;
  4116. S_L:
  4117. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4118. begin
  4119. taicpu(p).oper[0]^.val := -1;
  4120. Result := True;
  4121. Exit;
  4122. end;
  4123. {$ifdef x86_64}
  4124. S_Q:
  4125. { Storing anything greater than $7FFFFFFF is not possible so do
  4126. nothing };
  4127. {$endif x86_64}
  4128. else
  4129. InternalError(2021121001);
  4130. end;
  4131. end;
  4132. if GetNextInstruction(p, hp1) and
  4133. TrySwapMovCmp(p, hp1) then
  4134. begin
  4135. Result := True;
  4136. Exit;
  4137. end;
  4138. { Search for:
  4139. test $x,(reg/ref)
  4140. jne @lbl1
  4141. test $y,(reg/ref) (same register or reference)
  4142. jne @lbl1
  4143. Change to:
  4144. test $(x or y),(reg/ref)
  4145. jne @lbl1
  4146. (Note, this doesn't work with je instead of jne)
  4147. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4148. Also search for:
  4149. test $x,(reg/ref)
  4150. je @lbl1
  4151. test $y,(reg/ref)
  4152. je/jne @lbl2
  4153. If (x or y) = x, then the second jump is deterministic
  4154. }
  4155. if (
  4156. (
  4157. (taicpu(p).oper[0]^.typ = top_const) or
  4158. (
  4159. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4160. (taicpu(p).oper[0]^.typ = top_reg) and
  4161. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4162. )
  4163. ) and
  4164. MatchInstruction(hp1, A_JCC, [])
  4165. ) then
  4166. begin
  4167. if (taicpu(p).oper[0]^.typ = top_reg) and
  4168. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4169. FirstValue := -1
  4170. else
  4171. FirstValue := taicpu(p).oper[0]^.val;
  4172. { If we have several test/jne's in a row, it might be the case that
  4173. the second label doesn't go to the same location, but the one
  4174. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4175. so accommodate for this with a while loop.
  4176. }
  4177. hp1_dist := hp1;
  4178. if GetNextInstruction(hp1, p_dist) and
  4179. (p_dist.typ = ait_instruction) and
  4180. (
  4181. (
  4182. (taicpu(p_dist).opcode = A_TEST) and
  4183. (
  4184. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4185. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4186. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4187. )
  4188. ) or
  4189. (
  4190. { cmp 0,%reg = test %reg,%reg }
  4191. (taicpu(p_dist).opcode = A_CMP) and
  4192. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4193. )
  4194. ) and
  4195. { Make sure the destination operands are actually the same }
  4196. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4197. GetNextInstruction(p_dist, hp1_dist) and
  4198. MatchInstruction(hp1_dist, A_JCC, []) then
  4199. begin
  4200. if
  4201. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4202. (
  4203. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4204. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4205. ) then
  4206. SecondValue := -1
  4207. else
  4208. SecondValue := taicpu(p_dist).oper[0]^.val;
  4209. { If both of the TEST constants are identical, delete the second
  4210. TEST that is unnecessary. }
  4211. if (FirstValue = SecondValue) then
  4212. begin
  4213. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4214. RemoveInstruction(p_dist);
  4215. { Don't let the flags register become deallocated and reallocated between the jumps }
  4216. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4217. Result := True;
  4218. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4219. begin
  4220. { Since the second jump's condition is a subset of the first, we
  4221. know it will never branch because the first jump dominates it.
  4222. Get it out of the way now rather than wait for the jump
  4223. optimisations for a speed boost. }
  4224. if IsJumpToLabel(taicpu(hp1_dist)) then
  4225. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4226. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4227. RemoveInstruction(hp1_dist);
  4228. end
  4229. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4230. begin
  4231. { If the inverse of the first condition is a subset of the second,
  4232. the second one will definitely branch if the first one doesn't }
  4233. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4234. MakeUnconditional(taicpu(hp1_dist));
  4235. RemoveDeadCodeAfterJump(hp1_dist);
  4236. end;
  4237. Exit;
  4238. end;
  4239. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4240. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4241. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4242. then the second jump will never branch, so it can also be
  4243. removed regardless of where it goes }
  4244. (
  4245. (FirstValue = -1) or
  4246. (SecondValue = -1) or
  4247. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4248. ) then
  4249. begin
  4250. { Same jump location... can be a register since nothing's changed }
  4251. { If any of the entries are equivalent to test %reg,%reg, then the
  4252. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4253. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4254. if IsJumpToLabel(taicpu(hp1_dist)) then
  4255. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4256. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4257. RemoveInstruction(hp1_dist);
  4258. { Only remove the second test if no jumps or other conditional instructions follow }
  4259. TransferUsedRegs(TmpUsedRegs);
  4260. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4261. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4262. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4263. RemoveInstruction(p_dist);
  4264. Result := True;
  4265. Exit;
  4266. end;
  4267. end;
  4268. end;
  4269. { Search for:
  4270. test %reg,%reg
  4271. j(c1) @lbl1
  4272. ...
  4273. @lbl:
  4274. test %reg,%reg (same register)
  4275. j(c2) @lbl2
  4276. If c2 is a subset of c1, change to:
  4277. test %reg,%reg
  4278. j(c1) @lbl2
  4279. (@lbl1 may become a dead label as a result)
  4280. }
  4281. if (taicpu(p).oper[1]^.typ = top_reg) and
  4282. (taicpu(p).oper[0]^.typ = top_reg) and
  4283. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4284. MatchInstruction(hp1, A_JCC, []) and
  4285. IsJumpToLabel(taicpu(hp1)) then
  4286. begin
  4287. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4288. p_label := nil;
  4289. if Assigned(JumpLabel) then
  4290. p_label := getlabelwithsym(JumpLabel);
  4291. if Assigned(p_label) and
  4292. GetNextInstruction(p_label, p_dist) and
  4293. MatchInstruction(p_dist, A_TEST, []) and
  4294. { It's fine if the second test uses smaller sub-registers }
  4295. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4296. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4297. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4298. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4299. GetNextInstruction(p_dist, hp1_dist) and
  4300. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4301. begin
  4302. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4303. if JumpLabel = JumpLabel_dist then
  4304. { This is an infinite loop }
  4305. Exit;
  4306. { Best optimisation when the first condition is a subset (or equal) of the second }
  4307. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4308. begin
  4309. { Any registers used here will already be allocated }
  4310. if Assigned(JumpLabel_dist) then
  4311. JumpLabel_dist.IncRefs;
  4312. if Assigned(JumpLabel) then
  4313. JumpLabel.DecRefs;
  4314. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4315. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4316. Result := True;
  4317. Exit;
  4318. end;
  4319. end;
  4320. end;
  4321. end;
  4322. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4323. var
  4324. hp1, hp2: tai;
  4325. ActiveReg: TRegister;
  4326. OldOffset: asizeint;
  4327. ThisConst: TCGInt;
  4328. function RegDeallocated: Boolean;
  4329. begin
  4330. TransferUsedRegs(TmpUsedRegs);
  4331. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4332. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4333. end;
  4334. begin
  4335. result:=false;
  4336. hp1 := nil;
  4337. { replace
  4338. addX const,%reg1
  4339. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4340. dealloc %reg1
  4341. by
  4342. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4343. }
  4344. if MatchOpType(taicpu(p),top_const,top_reg) then
  4345. begin
  4346. ActiveReg := taicpu(p).oper[1]^.reg;
  4347. { Ensures the entire register was updated }
  4348. if (taicpu(p).opsize >= S_L) and
  4349. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4350. MatchInstruction(hp1,A_LEA,[]) and
  4351. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4352. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4353. (
  4354. { Cover the case where the register in the reference is also the destination register }
  4355. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4356. (
  4357. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4358. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4359. RegDeallocated
  4360. )
  4361. ) then
  4362. begin
  4363. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4364. {$push}
  4365. {$R-}{$Q-}
  4366. { Explicitly disable overflow checking for these offset calculation
  4367. as those do not matter for the final result }
  4368. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4369. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4370. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4371. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4372. {$pop}
  4373. {$ifdef x86_64}
  4374. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4375. begin
  4376. { Overflow; abort }
  4377. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4378. end
  4379. else
  4380. {$endif x86_64}
  4381. begin
  4382. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4383. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4384. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4385. RemoveCurrentP(p, hp1)
  4386. else
  4387. RemoveCurrentP(p);
  4388. result:=true;
  4389. Exit;
  4390. end;
  4391. end;
  4392. if (
  4393. { Save calling GetNextInstructionUsingReg again }
  4394. Assigned(hp1) or
  4395. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4396. ) and
  4397. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4398. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4399. begin
  4400. if taicpu(hp1).oper[0]^.typ = top_const then
  4401. begin
  4402. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4403. if taicpu(hp1).opcode = A_ADD then
  4404. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4405. else
  4406. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4407. Result := True;
  4408. { Handle any overflows }
  4409. case taicpu(p).opsize of
  4410. S_B:
  4411. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4412. S_W:
  4413. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4414. S_L:
  4415. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4416. {$ifdef x86_64}
  4417. S_Q:
  4418. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4419. { Overflow; abort }
  4420. Result := False
  4421. else
  4422. taicpu(p).oper[0]^.val := ThisConst;
  4423. {$endif x86_64}
  4424. else
  4425. InternalError(2021102610);
  4426. end;
  4427. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4428. if Result then
  4429. begin
  4430. if (taicpu(p).oper[0]^.val < 0) and
  4431. (
  4432. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4433. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4434. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4435. ) then
  4436. begin
  4437. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4438. taicpu(p).opcode := A_SUB;
  4439. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4440. end
  4441. else
  4442. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4443. RemoveInstruction(hp1);
  4444. end;
  4445. end
  4446. else
  4447. begin
  4448. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4449. TransferUsedRegs(TmpUsedRegs);
  4450. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4451. hp2 := p;
  4452. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4453. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4454. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4455. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4456. begin
  4457. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4458. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4459. Asml.Remove(p);
  4460. Asml.InsertAfter(p, hp1);
  4461. p := hp1;
  4462. Result := True;
  4463. end;
  4464. end;
  4465. end;
  4466. end;
  4467. end;
  4468. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4469. var
  4470. hp1: tai;
  4471. ref: Integer;
  4472. saveref: treference;
  4473. TempReg: TRegister;
  4474. Multiple: TCGInt;
  4475. begin
  4476. Result:=false;
  4477. { play save and throw an error if LEA uses a seg register prefix,
  4478. this is most likely an error somewhere else }
  4479. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  4480. internalerror(2022022001);
  4481. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4482. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4483. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4484. (
  4485. { do not mess with leas accessing the stack pointer
  4486. unless it's a null operation }
  4487. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4488. (
  4489. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4490. (taicpu(p).oper[0]^.ref^.offset = 0)
  4491. )
  4492. ) and
  4493. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4494. begin
  4495. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4496. begin
  4497. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4498. begin
  4499. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  4500. taicpu(p).oper[1]^.reg);
  4501. InsertLLItem(p.previous,p.next, hp1);
  4502. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  4503. p.free;
  4504. p:=hp1;
  4505. end
  4506. else
  4507. begin
  4508. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4509. RemoveCurrentP(p);
  4510. end;
  4511. Result:=true;
  4512. exit;
  4513. end
  4514. else if (
  4515. { continue to use lea to adjust the stack pointer,
  4516. it is the recommended way, but only if not optimizing for size }
  4517. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  4518. (cs_opt_size in current_settings.optimizerswitches)
  4519. ) and
  4520. { If the flags register is in use, don't change the instruction
  4521. to an ADD otherwise this will scramble the flags. [Kit] }
  4522. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  4523. ConvertLEA(taicpu(p)) then
  4524. begin
  4525. Result:=true;
  4526. exit;
  4527. end;
  4528. end;
  4529. if GetNextInstruction(p,hp1) and
  4530. (hp1.typ=ait_instruction) then
  4531. begin
  4532. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  4533. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4534. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  4535. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  4536. begin
  4537. TransferUsedRegs(TmpUsedRegs);
  4538. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4539. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4540. begin
  4541. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4542. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  4543. RemoveInstruction(hp1);
  4544. result:=true;
  4545. exit;
  4546. end;
  4547. end;
  4548. { changes
  4549. lea <ref1>, reg1
  4550. <op> ...,<ref. with reg1>,...
  4551. to
  4552. <op> ...,<ref1>,... }
  4553. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  4554. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  4555. not(MatchInstruction(hp1,A_LEA,[])) then
  4556. begin
  4557. { find a reference which uses reg1 }
  4558. 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
  4559. ref:=0
  4560. 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
  4561. ref:=1
  4562. else
  4563. ref:=-1;
  4564. if (ref<>-1) and
  4565. { reg1 must be either the base or the index }
  4566. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  4567. begin
  4568. { reg1 can be removed from the reference }
  4569. saveref:=taicpu(hp1).oper[ref]^.ref^;
  4570. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  4571. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  4572. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  4573. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  4574. else
  4575. Internalerror(2019111201);
  4576. { check if the can insert all data of the lea into the second instruction }
  4577. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4578. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  4579. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  4580. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  4581. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  4582. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  4583. { Segment register of p.oper[0]^.ref will be NR_NO already }
  4584. (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  4585. {$ifdef x86_64}
  4586. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  4587. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  4588. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  4589. )
  4590. {$endif x86_64}
  4591. then
  4592. begin
  4593. { reg1 might not used by the second instruction after it is remove from the reference }
  4594. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  4595. begin
  4596. TransferUsedRegs(TmpUsedRegs);
  4597. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4598. { reg1 is not updated so it might not be used afterwards }
  4599. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4600. begin
  4601. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  4602. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  4603. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4604. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4605. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4606. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  4607. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  4608. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  4609. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  4610. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  4611. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4612. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4613. RemoveCurrentP(p, hp1);
  4614. result:=true;
  4615. exit;
  4616. end
  4617. end;
  4618. end;
  4619. { recover }
  4620. taicpu(hp1).oper[ref]^.ref^:=saveref;
  4621. end;
  4622. end;
  4623. end;
  4624. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  4625. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  4626. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  4627. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  4628. begin
  4629. { Check common LEA/LEA conditions }
  4630. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  4631. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  4632. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  4633. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  4634. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  4635. { Since we're merging two LEA instructions, the segment registers don't matter }
  4636. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  4637. (
  4638. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  4639. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  4640. ) and (
  4641. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  4642. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4643. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  4644. ) then
  4645. begin
  4646. { changes
  4647. lea (regX,scale), reg1
  4648. lea offset(reg1,reg1), reg1
  4649. to
  4650. lea offset(regX,scale*2), reg1
  4651. and
  4652. lea (regX,scale1), reg1
  4653. lea offset(reg1,scale2), reg1
  4654. to
  4655. lea offset(regX,scale1*scale2), reg1
  4656. ... so long as the final scale does not exceed 8
  4657. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  4658. }
  4659. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  4660. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4661. (
  4662. (
  4663. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4664. ) or (
  4665. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4666. (
  4667. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  4668. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  4669. )
  4670. )
  4671. ) and (
  4672. (
  4673. { lea (reg1,scale2), reg1 variant }
  4674. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  4675. (
  4676. (
  4677. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  4678. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  4679. ) or (
  4680. { lea (regX,regX), reg1 variant }
  4681. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4682. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  4683. )
  4684. )
  4685. ) or (
  4686. { lea (reg1,reg1), reg1 variant }
  4687. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4688. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  4689. )
  4690. ) then
  4691. begin
  4692. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  4693. { Make everything homogeneous to make calculations easier }
  4694. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  4695. begin
  4696. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  4697. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  4698. taicpu(p).oper[0]^.ref^.scalefactor := 2
  4699. else
  4700. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  4701. taicpu(p).oper[0]^.ref^.base := NR_NO;
  4702. end;
  4703. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  4704. begin
  4705. { Just to prevent miscalculations }
  4706. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  4707. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  4708. else
  4709. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  4710. end
  4711. else
  4712. begin
  4713. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  4714. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  4715. end;
  4716. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  4717. RemoveCurrentP(p);
  4718. result:=true;
  4719. exit;
  4720. end
  4721. { changes
  4722. lea offset1(regX), reg1
  4723. lea offset2(reg1), reg1
  4724. to
  4725. lea offset1+offset2(regX), reg1 }
  4726. else if
  4727. (
  4728. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4729. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  4730. ) or (
  4731. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  4732. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  4733. (
  4734. (
  4735. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4736. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  4737. ) or (
  4738. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  4739. (
  4740. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4741. (
  4742. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4743. (
  4744. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  4745. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  4746. )
  4747. )
  4748. )
  4749. )
  4750. )
  4751. ) then
  4752. begin
  4753. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  4754. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  4755. begin
  4756. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  4757. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4758. { if the register is used as index and base, we have to increase for base as well
  4759. and adapt base }
  4760. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  4761. begin
  4762. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4763. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4764. end;
  4765. end
  4766. else
  4767. begin
  4768. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  4769. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  4770. end;
  4771. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  4772. begin
  4773. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  4774. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  4775. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  4776. end;
  4777. RemoveCurrentP(p);
  4778. result:=true;
  4779. exit;
  4780. end;
  4781. end;
  4782. { Change:
  4783. leal/q $x(%reg1),%reg2
  4784. ...
  4785. shll/q $y,%reg2
  4786. To:
  4787. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  4788. }
  4789. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  4790. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4791. (taicpu(hp1).oper[0]^.val <= 3) then
  4792. begin
  4793. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  4794. TransferUsedRegs(TmpUsedRegs);
  4795. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4796. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  4797. if
  4798. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  4799. (this works even if scalefactor is zero) }
  4800. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  4801. { Ensure offset doesn't go out of bounds }
  4802. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  4803. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  4804. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  4805. (
  4806. (
  4807. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  4808. (
  4809. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  4810. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  4811. (
  4812. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  4813. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  4814. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  4815. )
  4816. )
  4817. ) or (
  4818. (
  4819. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  4820. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  4821. ) and
  4822. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  4823. )
  4824. ) then
  4825. begin
  4826. repeat
  4827. with taicpu(p).oper[0]^.ref^ do
  4828. begin
  4829. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  4830. if index = base then
  4831. begin
  4832. if Multiple > 4 then
  4833. { Optimisation will no longer work because resultant
  4834. scale factor will exceed 8 }
  4835. Break;
  4836. base := NR_NO;
  4837. scalefactor := 2;
  4838. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  4839. end
  4840. else if (base <> NR_NO) and (base <> NR_INVALID) then
  4841. begin
  4842. { Scale factor only works on the index register }
  4843. index := base;
  4844. base := NR_NO;
  4845. end;
  4846. { For safety }
  4847. if scalefactor <= 1 then
  4848. begin
  4849. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  4850. scalefactor := Multiple;
  4851. end
  4852. else
  4853. begin
  4854. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  4855. scalefactor := scalefactor * Multiple;
  4856. end;
  4857. offset := offset * Multiple;
  4858. end;
  4859. RemoveInstruction(hp1);
  4860. Result := True;
  4861. Exit;
  4862. { This repeat..until loop exists for the benefit of Break }
  4863. until True;
  4864. end;
  4865. end;
  4866. end;
  4867. end;
  4868. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  4869. var
  4870. hp1 : tai;
  4871. begin
  4872. DoSubAddOpt := False;
  4873. if taicpu(p).oper[0]^.typ <> top_const then
  4874. { Should have been confirmed before calling }
  4875. InternalError(2021102601);
  4876. if GetLastInstruction(p, hp1) and
  4877. (hp1.typ = ait_instruction) and
  4878. (taicpu(hp1).opsize = taicpu(p).opsize) then
  4879. case taicpu(hp1).opcode Of
  4880. A_DEC:
  4881. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4882. begin
  4883. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  4884. RemoveInstruction(hp1);
  4885. end;
  4886. A_SUB:
  4887. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4888. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4889. begin
  4890. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  4891. RemoveInstruction(hp1);
  4892. end;
  4893. A_ADD:
  4894. begin
  4895. if (taicpu(hp1).oper[0]^.typ = top_const) and
  4896. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  4897. begin
  4898. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  4899. RemoveInstruction(hp1);
  4900. if (taicpu(p).oper[0]^.val = 0) then
  4901. begin
  4902. hp1 := tai(p.next);
  4903. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  4904. if not GetLastInstruction(hp1, p) then
  4905. p := hp1;
  4906. DoSubAddOpt := True;
  4907. end
  4908. end;
  4909. end;
  4910. else
  4911. ;
  4912. end;
  4913. end;
  4914. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  4915. begin
  4916. Result := False;
  4917. if UpdateTmpUsedRegs then
  4918. TransferUsedRegs(TmpUsedRegs);
  4919. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4920. { The x86 assemblers have difficulty comparing values against absolute addresses }
  4921. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  4922. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  4923. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  4924. (
  4925. (
  4926. (taicpu(hp1).opcode = A_TEST)
  4927. ) or (
  4928. (taicpu(hp1).opcode = A_CMP) and
  4929. { A sanity check more than anything }
  4930. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  4931. )
  4932. ) then
  4933. begin
  4934. { change
  4935. mov mem, %reg
  4936. cmp/test x, %reg / test %reg,%reg
  4937. (reg deallocated)
  4938. to
  4939. cmp/test x, mem / cmp 0, mem
  4940. }
  4941. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4942. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  4943. begin
  4944. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  4945. if (taicpu(hp1).opcode = A_TEST) and
  4946. (
  4947. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  4948. MatchOperand(taicpu(hp1).oper[0]^, -1)
  4949. ) then
  4950. begin
  4951. taicpu(hp1).opcode := A_CMP;
  4952. taicpu(hp1).loadconst(0, 0);
  4953. end;
  4954. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  4955. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  4956. RemoveCurrentP(p, hp1);
  4957. Result := True;
  4958. Exit;
  4959. end;
  4960. end;
  4961. end;
  4962. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  4963. var
  4964. hp2, hp3, hp4, hp5, hp6: tai;
  4965. ThisReg: TRegister;
  4966. JumpLoc: TAsmLabel;
  4967. begin
  4968. Result := False;
  4969. {
  4970. Convert:
  4971. j<c> .L1
  4972. .L2:
  4973. mov 1,reg
  4974. jmp .L3 (or ret, although it might not be a RET yet)
  4975. .L1:
  4976. mov 0,reg
  4977. jmp .L3 (or ret)
  4978. ( As long as .L3 <> .L1 or .L2)
  4979. To:
  4980. mov 0,reg
  4981. set<not(c)> reg
  4982. jmp .L3 (or ret)
  4983. .L2:
  4984. mov 1,reg
  4985. jmp .L3 (or ret)
  4986. .L1:
  4987. mov 0,reg
  4988. jmp .L3 (or ret)
  4989. }
  4990. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  4991. Exit;
  4992. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  4993. if GetNextInstruction(hp_label, hp2) and
  4994. MatchInstruction(hp2,A_MOV,[]) and
  4995. (taicpu(hp2).oper[0]^.typ = top_const) and
  4996. (
  4997. (
  4998. (taicpu(hp2).oper[1]^.typ = top_reg)
  4999. {$ifdef i386}
  5000. { Under i386, ESI, EDI, EBP and ESP
  5001. don't have an 8-bit representation }
  5002. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5003. {$endif i386}
  5004. ) or (
  5005. {$ifdef i386}
  5006. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5007. {$endif i386}
  5008. (taicpu(hp2).opsize = S_B)
  5009. )
  5010. ) and
  5011. GetNextInstruction(hp2, hp3) and
  5012. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5013. (
  5014. (taicpu(hp3).opcode=A_RET) or
  5015. (
  5016. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5017. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5018. )
  5019. ) and
  5020. GetNextInstruction(hp3, hp4) and
  5021. SkipAligns(hp4, hp4) and
  5022. (hp4.typ=ait_label) and
  5023. (tai_label(hp4).labsym=JumpLoc) and
  5024. (
  5025. not (cs_opt_size in current_settings.optimizerswitches) or
  5026. { If the initial jump is the label's only reference, then it will
  5027. become a dead label if the other conditions are met and hence
  5028. remove at least 2 instructions, including a jump }
  5029. (JumpLoc.getrefs = 1)
  5030. ) and
  5031. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5032. that will be optimised out }
  5033. GetNextInstruction(hp4, hp5) and
  5034. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5035. (taicpu(hp5).oper[0]^.typ = top_const) and
  5036. (
  5037. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5038. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5039. ) and
  5040. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5041. GetNextInstruction(hp5,hp6) and
  5042. (
  5043. (hp6.typ<>ait_label) or
  5044. SkipLabels(hp6, hp6)
  5045. ) and
  5046. (hp6.typ=ait_instruction) then
  5047. begin
  5048. { First, let's look at the two jumps that are hp3 and hp6 }
  5049. if not
  5050. (
  5051. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5052. (
  5053. (taicpu(hp6).opcode=A_RET) or
  5054. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5055. )
  5056. ) then
  5057. { If condition is False, then the JMP/RET instructions matched conventionally }
  5058. begin
  5059. { See if one of the jumps can be instantly converted into a RET }
  5060. if (taicpu(hp3).opcode=A_JMP) then
  5061. begin
  5062. { Reuse hp5 }
  5063. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5064. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5065. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5066. Exit;
  5067. if MatchInstruction(hp5, A_RET, []) then
  5068. begin
  5069. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5070. ConvertJumpToRET(hp3, hp5);
  5071. Result := True;
  5072. end
  5073. else
  5074. Exit;
  5075. end;
  5076. if (taicpu(hp6).opcode=A_JMP) then
  5077. begin
  5078. { Reuse hp5 }
  5079. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5080. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5081. Exit;
  5082. if MatchInstruction(hp5, A_RET, []) then
  5083. begin
  5084. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5085. ConvertJumpToRET(hp6, hp5);
  5086. Result := True;
  5087. end
  5088. else
  5089. Exit;
  5090. end;
  5091. if not
  5092. (
  5093. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5094. (
  5095. (taicpu(hp6).opcode=A_RET) or
  5096. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5097. )
  5098. ) then
  5099. { Still doesn't match }
  5100. Exit;
  5101. end;
  5102. if (taicpu(hp2).oper[0]^.val = 1) then
  5103. begin
  5104. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5105. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5106. end
  5107. else
  5108. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5109. if taicpu(hp2).opsize=S_B then
  5110. begin
  5111. if taicpu(hp2).oper[1]^.typ = top_reg then
  5112. hp4:=taicpu.op_reg(A_SETcc, S_B, taicpu(hp2).oper[1]^.reg)
  5113. else
  5114. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5115. hp2 := p;
  5116. end
  5117. else
  5118. begin
  5119. { Will be a register because the size can't be S_B otherwise }
  5120. ThisReg:=newreg(R_INTREGISTER,getsupreg(taicpu(hp2).oper[1]^.reg), R_SUBL);
  5121. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5122. hp2:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, taicpu(hp2).oper[1]^.reg);
  5123. { Inserting it right before p will guarantee that the flags are also tracked }
  5124. Asml.InsertBefore(hp2, p);
  5125. end;
  5126. taicpu(hp4).condition:=taicpu(p).condition;
  5127. asml.InsertBefore(hp4, hp2);
  5128. JumpLoc.decrefs;
  5129. if taicpu(hp3).opcode = A_JMP then
  5130. begin
  5131. MakeUnconditional(taicpu(p));
  5132. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5133. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5134. end
  5135. else
  5136. begin
  5137. taicpu(p).condition := C_None;
  5138. taicpu(p).opcode := A_RET;
  5139. taicpu(p).clearop(0);
  5140. taicpu(p).ops := 0;
  5141. end;
  5142. if (JumpLoc.getrefs = 0) then
  5143. RemoveDeadCodeAfterJump(hp3);
  5144. Result:=true;
  5145. exit;
  5146. end;
  5147. end;
  5148. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5149. var
  5150. hp1, hp2: tai;
  5151. ActiveReg: TRegister;
  5152. OldOffset: asizeint;
  5153. ThisConst: TCGInt;
  5154. function RegDeallocated: Boolean;
  5155. begin
  5156. TransferUsedRegs(TmpUsedRegs);
  5157. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5158. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5159. end;
  5160. begin
  5161. Result:=false;
  5162. hp1 := nil;
  5163. { replace
  5164. subX const,%reg1
  5165. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5166. dealloc %reg1
  5167. by
  5168. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5169. }
  5170. if MatchOpType(taicpu(p),top_const,top_reg) then
  5171. begin
  5172. ActiveReg := taicpu(p).oper[1]^.reg;
  5173. { Ensures the entire register was updated }
  5174. if (taicpu(p).opsize >= S_L) and
  5175. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5176. MatchInstruction(hp1,A_LEA,[]) and
  5177. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5178. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5179. (
  5180. { Cover the case where the register in the reference is also the destination register }
  5181. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5182. (
  5183. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5184. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5185. RegDeallocated
  5186. )
  5187. ) then
  5188. begin
  5189. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5190. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5191. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5192. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5193. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5194. {$ifdef x86_64}
  5195. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5196. begin
  5197. { Overflow; abort }
  5198. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5199. end
  5200. else
  5201. {$endif x86_64}
  5202. begin
  5203. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5204. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5205. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5206. RemoveCurrentP(p, hp1)
  5207. else
  5208. RemoveCurrentP(p);
  5209. result:=true;
  5210. Exit;
  5211. end;
  5212. end;
  5213. if (
  5214. { Save calling GetNextInstructionUsingReg again }
  5215. Assigned(hp1) or
  5216. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5217. ) and
  5218. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5219. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5220. begin
  5221. if taicpu(hp1).oper[0]^.typ = top_const then
  5222. begin
  5223. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5224. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5225. Result := True;
  5226. { Handle any overflows }
  5227. case taicpu(p).opsize of
  5228. S_B:
  5229. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5230. S_W:
  5231. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5232. S_L:
  5233. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5234. {$ifdef x86_64}
  5235. S_Q:
  5236. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5237. { Overflow; abort }
  5238. Result := False
  5239. else
  5240. taicpu(p).oper[0]^.val := ThisConst;
  5241. {$endif x86_64}
  5242. else
  5243. InternalError(2021102610);
  5244. end;
  5245. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5246. if Result then
  5247. begin
  5248. if (taicpu(p).oper[0]^.val < 0) and
  5249. (
  5250. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5251. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5252. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5253. ) then
  5254. begin
  5255. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5256. taicpu(p).opcode := A_SUB;
  5257. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5258. end
  5259. else
  5260. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5261. RemoveInstruction(hp1);
  5262. end;
  5263. end
  5264. else
  5265. begin
  5266. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5267. TransferUsedRegs(TmpUsedRegs);
  5268. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5269. hp2 := p;
  5270. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5271. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5272. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5273. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5274. begin
  5275. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5276. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5277. Asml.Remove(p);
  5278. Asml.InsertAfter(p, hp1);
  5279. p := hp1;
  5280. Result := True;
  5281. Exit;
  5282. end;
  5283. end;
  5284. end;
  5285. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5286. { * change "sub/add const1, reg" or "dec reg" followed by
  5287. "sub const2, reg" to one "sub ..., reg" }
  5288. {$ifdef i386}
  5289. if (taicpu(p).oper[0]^.val = 2) and
  5290. (ActiveReg = NR_ESP) and
  5291. { Don't do the sub/push optimization if the sub }
  5292. { comes from setting up the stack frame (JM) }
  5293. (not(GetLastInstruction(p,hp1)) or
  5294. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5295. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5296. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5297. begin
  5298. hp1 := tai(p.next);
  5299. while Assigned(hp1) and
  5300. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5301. not RegReadByInstruction(NR_ESP,hp1) and
  5302. not RegModifiedByInstruction(NR_ESP,hp1) do
  5303. hp1 := tai(hp1.next);
  5304. if Assigned(hp1) and
  5305. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5306. begin
  5307. taicpu(hp1).changeopsize(S_L);
  5308. if taicpu(hp1).oper[0]^.typ=top_reg then
  5309. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5310. hp1 := tai(p.next);
  5311. RemoveCurrentp(p, hp1);
  5312. Result:=true;
  5313. exit;
  5314. end;
  5315. end;
  5316. {$endif i386}
  5317. if DoSubAddOpt(p) then
  5318. Result:=true;
  5319. end;
  5320. end;
  5321. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5322. var
  5323. TmpBool1,TmpBool2 : Boolean;
  5324. tmpref : treference;
  5325. hp1,hp2: tai;
  5326. mask: tcgint;
  5327. begin
  5328. Result:=false;
  5329. { All these optimisations work on "shl/sal const,%reg" }
  5330. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5331. Exit;
  5332. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5333. (taicpu(p).oper[0]^.val <= 3) then
  5334. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5335. begin
  5336. { should we check the next instruction? }
  5337. TmpBool1 := True;
  5338. { have we found an add/sub which could be
  5339. integrated in the lea? }
  5340. TmpBool2 := False;
  5341. reference_reset(tmpref,2,[]);
  5342. TmpRef.index := taicpu(p).oper[1]^.reg;
  5343. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5344. while TmpBool1 and
  5345. GetNextInstruction(p, hp1) and
  5346. (tai(hp1).typ = ait_instruction) and
  5347. ((((taicpu(hp1).opcode = A_ADD) or
  5348. (taicpu(hp1).opcode = A_SUB)) and
  5349. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5350. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5351. (((taicpu(hp1).opcode = A_INC) or
  5352. (taicpu(hp1).opcode = A_DEC)) and
  5353. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5354. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5355. ((taicpu(hp1).opcode = A_LEA) and
  5356. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5357. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5358. (not GetNextInstruction(hp1,hp2) or
  5359. not instrReadsFlags(hp2)) Do
  5360. begin
  5361. TmpBool1 := False;
  5362. if taicpu(hp1).opcode=A_LEA then
  5363. begin
  5364. if (TmpRef.base = NR_NO) and
  5365. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5366. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5367. { Segment register isn't a concern here }
  5368. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5369. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5370. begin
  5371. TmpBool1 := True;
  5372. TmpBool2 := True;
  5373. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5374. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5375. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5376. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5377. RemoveInstruction(hp1);
  5378. end
  5379. end
  5380. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5381. begin
  5382. TmpBool1 := True;
  5383. TmpBool2 := True;
  5384. case taicpu(hp1).opcode of
  5385. A_ADD:
  5386. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5387. A_SUB:
  5388. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5389. else
  5390. internalerror(2019050536);
  5391. end;
  5392. RemoveInstruction(hp1);
  5393. end
  5394. else
  5395. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5396. (((taicpu(hp1).opcode = A_ADD) and
  5397. (TmpRef.base = NR_NO)) or
  5398. (taicpu(hp1).opcode = A_INC) or
  5399. (taicpu(hp1).opcode = A_DEC)) then
  5400. begin
  5401. TmpBool1 := True;
  5402. TmpBool2 := True;
  5403. case taicpu(hp1).opcode of
  5404. A_ADD:
  5405. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5406. A_INC:
  5407. inc(TmpRef.offset);
  5408. A_DEC:
  5409. dec(TmpRef.offset);
  5410. else
  5411. internalerror(2019050535);
  5412. end;
  5413. RemoveInstruction(hp1);
  5414. end;
  5415. end;
  5416. if TmpBool2
  5417. {$ifndef x86_64}
  5418. or
  5419. ((current_settings.optimizecputype < cpu_Pentium2) and
  5420. (taicpu(p).oper[0]^.val <= 3) and
  5421. not(cs_opt_size in current_settings.optimizerswitches))
  5422. {$endif x86_64}
  5423. then
  5424. begin
  5425. if not(TmpBool2) and
  5426. (taicpu(p).oper[0]^.val=1) then
  5427. begin
  5428. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5429. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5430. end
  5431. else
  5432. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  5433. taicpu(p).oper[1]^.reg);
  5434. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  5435. InsertLLItem(p.previous, p.next, hp1);
  5436. p.free;
  5437. p := hp1;
  5438. end;
  5439. end
  5440. {$ifndef x86_64}
  5441. else if (current_settings.optimizecputype < cpu_Pentium2) then
  5442. begin
  5443. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  5444. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  5445. (unlike shl, which is only Tairable in the U pipe) }
  5446. if taicpu(p).oper[0]^.val=1 then
  5447. begin
  5448. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  5449. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  5450. InsertLLItem(p.previous, p.next, hp1);
  5451. p.free;
  5452. p := hp1;
  5453. end
  5454. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  5455. "shl $3, %reg" to "lea (,%reg,8), %reg }
  5456. else if (taicpu(p).opsize = S_L) and
  5457. (taicpu(p).oper[0]^.val<= 3) then
  5458. begin
  5459. reference_reset(tmpref,2,[]);
  5460. TmpRef.index := taicpu(p).oper[1]^.reg;
  5461. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5462. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  5463. InsertLLItem(p.previous, p.next, hp1);
  5464. p.free;
  5465. p := hp1;
  5466. end;
  5467. end
  5468. {$endif x86_64}
  5469. else if
  5470. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  5471. (
  5472. (
  5473. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  5474. SetAndTest(hp1, hp2)
  5475. {$ifdef x86_64}
  5476. ) or
  5477. (
  5478. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  5479. GetNextInstruction(hp1, hp2) and
  5480. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  5481. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5482. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  5483. {$endif x86_64}
  5484. )
  5485. ) and
  5486. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  5487. begin
  5488. { Change:
  5489. shl x, %reg1
  5490. mov -(1<<x), %reg2
  5491. and %reg2, %reg1
  5492. Or:
  5493. shl x, %reg1
  5494. and -(1<<x), %reg1
  5495. To just:
  5496. shl x, %reg1
  5497. Since the and operation only zeroes bits that are already zero from the shl operation
  5498. }
  5499. case taicpu(p).oper[0]^.val of
  5500. 8:
  5501. mask:=$FFFFFFFFFFFFFF00;
  5502. 16:
  5503. mask:=$FFFFFFFFFFFF0000;
  5504. 32:
  5505. mask:=$FFFFFFFF00000000;
  5506. 63:
  5507. { Constant pre-calculated to prevent overflow errors with Int64 }
  5508. mask:=$8000000000000000;
  5509. else
  5510. begin
  5511. if taicpu(p).oper[0]^.val >= 64 then
  5512. { Shouldn't happen realistically, since the register
  5513. is guaranteed to be set to zero at this point }
  5514. mask := 0
  5515. else
  5516. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  5517. end;
  5518. end;
  5519. if taicpu(hp1).oper[0]^.val = mask then
  5520. begin
  5521. { Everything checks out, perform the optimisation, as long as
  5522. the FLAGS register isn't being used}
  5523. TransferUsedRegs(TmpUsedRegs);
  5524. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5525. {$ifdef x86_64}
  5526. if (hp1 <> hp2) then
  5527. begin
  5528. { "shl/mov/and" version }
  5529. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  5530. { Don't do the optimisation if the FLAGS register is in use }
  5531. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  5532. begin
  5533. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  5534. { Don't remove the 'mov' instruction if its register is used elsewhere }
  5535. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  5536. begin
  5537. RemoveInstruction(hp1);
  5538. Result := True;
  5539. end;
  5540. { Only set Result to True if the 'mov' instruction was removed }
  5541. RemoveInstruction(hp2);
  5542. end;
  5543. end
  5544. else
  5545. {$endif x86_64}
  5546. begin
  5547. { "shl/and" version }
  5548. { Don't do the optimisation if the FLAGS register is in use }
  5549. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  5550. begin
  5551. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  5552. RemoveInstruction(hp1);
  5553. Result := True;
  5554. end;
  5555. end;
  5556. Exit;
  5557. end
  5558. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  5559. begin
  5560. { Even if the mask doesn't allow for its removal, we might be
  5561. able to optimise the mask for the "shl/and" version, which
  5562. may permit other peephole optimisations }
  5563. {$ifdef DEBUG_AOPTCPU}
  5564. mask := taicpu(hp1).oper[0]^.val and mask;
  5565. if taicpu(hp1).oper[0]^.val <> mask then
  5566. begin
  5567. DebugMsg(
  5568. SPeepholeOptimization +
  5569. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  5570. ' to $' + debug_tostr(mask) +
  5571. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  5572. taicpu(hp1).oper[0]^.val := mask;
  5573. end;
  5574. {$else DEBUG_AOPTCPU}
  5575. { If debugging is off, just set the operand even if it's the same }
  5576. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  5577. {$endif DEBUG_AOPTCPU}
  5578. end;
  5579. end;
  5580. {
  5581. change
  5582. shl/sal const,reg
  5583. <op> ...(...,reg,1),...
  5584. into
  5585. <op> ...(...,reg,1 shl const),...
  5586. if const in 1..3
  5587. }
  5588. if MatchOpType(taicpu(p), top_const, top_reg) and
  5589. (taicpu(p).oper[0]^.val in [1..3]) and
  5590. GetNextInstruction(p, hp1) and
  5591. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  5592. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  5593. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  5594. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  5595. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  5596. begin
  5597. TransferUsedRegs(TmpUsedRegs);
  5598. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5599. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  5600. begin
  5601. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  5602. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  5603. RemoveCurrentP(p);
  5604. Result:=true;
  5605. end;
  5606. end;
  5607. end;
  5608. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  5609. var
  5610. CurrentRef: TReference;
  5611. FullReg: TRegister;
  5612. hp1, hp2: tai;
  5613. begin
  5614. Result := False;
  5615. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  5616. Exit;
  5617. { We assume you've checked if the operand is actually a reference by
  5618. this point. If it isn't, you'll most likely get an access violation }
  5619. CurrentRef := first_mov.oper[1]^.ref^;
  5620. { Memory must be aligned }
  5621. if (CurrentRef.offset mod 4) <> 0 then
  5622. Exit;
  5623. Inc(CurrentRef.offset);
  5624. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5625. if MatchOperand(second_mov.oper[0]^, 0) and
  5626. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  5627. GetNextInstruction(second_mov, hp1) and
  5628. (hp1.typ = ait_instruction) and
  5629. (taicpu(hp1).opcode = A_MOV) and
  5630. MatchOpType(taicpu(hp1), top_const, top_ref) and
  5631. (taicpu(hp1).oper[0]^.val = 0) then
  5632. begin
  5633. Inc(CurrentRef.offset);
  5634. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  5635. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  5636. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  5637. begin
  5638. case taicpu(hp1).opsize of
  5639. S_B:
  5640. if GetNextInstruction(hp1, hp2) and
  5641. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  5642. MatchOpType(taicpu(hp2), top_const, top_ref) and
  5643. (taicpu(hp2).oper[0]^.val = 0) then
  5644. begin
  5645. Inc(CurrentRef.offset);
  5646. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  5647. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  5648. (taicpu(hp2).opsize = S_B) then
  5649. begin
  5650. RemoveInstruction(hp1);
  5651. RemoveInstruction(hp2);
  5652. first_mov.opsize := S_L;
  5653. if first_mov.oper[0]^.typ = top_reg then
  5654. begin
  5655. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  5656. { Reuse second_mov as a MOVZX instruction }
  5657. second_mov.opcode := A_MOVZX;
  5658. second_mov.opsize := S_BL;
  5659. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5660. second_mov.loadreg(1, FullReg);
  5661. first_mov.oper[0]^.reg := FullReg;
  5662. asml.Remove(second_mov);
  5663. asml.InsertBefore(second_mov, first_mov);
  5664. end
  5665. else
  5666. { It's a value }
  5667. begin
  5668. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  5669. RemoveInstruction(second_mov);
  5670. end;
  5671. Result := True;
  5672. Exit;
  5673. end;
  5674. end;
  5675. S_W:
  5676. begin
  5677. RemoveInstruction(hp1);
  5678. first_mov.opsize := S_L;
  5679. if first_mov.oper[0]^.typ = top_reg then
  5680. begin
  5681. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  5682. { Reuse second_mov as a MOVZX instruction }
  5683. second_mov.opcode := A_MOVZX;
  5684. second_mov.opsize := S_BL;
  5685. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  5686. second_mov.loadreg(1, FullReg);
  5687. first_mov.oper[0]^.reg := FullReg;
  5688. asml.Remove(second_mov);
  5689. asml.InsertBefore(second_mov, first_mov);
  5690. end
  5691. else
  5692. { It's a value }
  5693. begin
  5694. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  5695. RemoveInstruction(second_mov);
  5696. end;
  5697. Result := True;
  5698. Exit;
  5699. end;
  5700. else
  5701. ;
  5702. end;
  5703. end;
  5704. end;
  5705. end;
  5706. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  5707. { returns true if a "continue" should be done after this optimization }
  5708. var
  5709. hp1, hp2: tai;
  5710. begin
  5711. Result := false;
  5712. if MatchOpType(taicpu(p),top_ref) and
  5713. GetNextInstruction(p, hp1) and
  5714. (hp1.typ = ait_instruction) and
  5715. (((taicpu(hp1).opcode = A_FLD) and
  5716. (taicpu(p).opcode = A_FSTP)) or
  5717. ((taicpu(p).opcode = A_FISTP) and
  5718. (taicpu(hp1).opcode = A_FILD))) and
  5719. MatchOpType(taicpu(hp1),top_ref) and
  5720. (taicpu(hp1).opsize = taicpu(p).opsize) and
  5721. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5722. begin
  5723. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  5724. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  5725. GetNextInstruction(hp1, hp2) and
  5726. (hp2.typ = ait_instruction) and
  5727. IsExitCode(hp2) and
  5728. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  5729. not(assigned(current_procinfo.procdef.funcretsym) and
  5730. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  5731. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  5732. begin
  5733. RemoveInstruction(hp1);
  5734. RemoveCurrentP(p, hp2);
  5735. RemoveLastDeallocForFuncRes(p);
  5736. Result := true;
  5737. end
  5738. else
  5739. { we can do this only in fast math mode as fstp is rounding ...
  5740. ... still disabled as it breaks the compiler and/or rtl }
  5741. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  5742. { ... or if another fstp equal to the first one follows }
  5743. (GetNextInstruction(hp1,hp2) and
  5744. (hp2.typ = ait_instruction) and
  5745. (taicpu(p).opcode=taicpu(hp2).opcode) and
  5746. (taicpu(p).opsize=taicpu(hp2).opsize))
  5747. ) and
  5748. { fst can't store an extended/comp value }
  5749. (taicpu(p).opsize <> S_FX) and
  5750. (taicpu(p).opsize <> S_IQ) then
  5751. begin
  5752. if (taicpu(p).opcode = A_FSTP) then
  5753. taicpu(p).opcode := A_FST
  5754. else
  5755. taicpu(p).opcode := A_FIST;
  5756. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  5757. RemoveInstruction(hp1);
  5758. end;
  5759. end;
  5760. end;
  5761. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  5762. var
  5763. hp1, hp2: tai;
  5764. begin
  5765. result:=false;
  5766. if MatchOpType(taicpu(p),top_reg) and
  5767. GetNextInstruction(p, hp1) and
  5768. (hp1.typ = Ait_Instruction) and
  5769. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5770. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  5771. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  5772. { change to
  5773. fld reg fxxx reg,st
  5774. fxxxp st, st1 (hp1)
  5775. Remark: non commutative operations must be reversed!
  5776. }
  5777. begin
  5778. case taicpu(hp1).opcode Of
  5779. A_FMULP,A_FADDP,
  5780. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5781. begin
  5782. case taicpu(hp1).opcode Of
  5783. A_FADDP: taicpu(hp1).opcode := A_FADD;
  5784. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  5785. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  5786. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  5787. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  5788. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  5789. else
  5790. internalerror(2019050534);
  5791. end;
  5792. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5793. taicpu(hp1).oper[1]^.reg := NR_ST;
  5794. RemoveCurrentP(p, hp1);
  5795. Result:=true;
  5796. exit;
  5797. end;
  5798. else
  5799. ;
  5800. end;
  5801. end
  5802. else
  5803. if MatchOpType(taicpu(p),top_ref) and
  5804. GetNextInstruction(p, hp2) and
  5805. (hp2.typ = Ait_Instruction) and
  5806. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  5807. (taicpu(p).opsize in [S_FS, S_FL]) and
  5808. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  5809. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  5810. if GetLastInstruction(p, hp1) and
  5811. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  5812. MatchOpType(taicpu(hp1),top_ref) and
  5813. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  5814. if ((taicpu(hp2).opcode = A_FMULP) or
  5815. (taicpu(hp2).opcode = A_FADDP)) then
  5816. { change to
  5817. fld/fst mem1 (hp1) fld/fst mem1
  5818. fld mem1 (p) fadd/
  5819. faddp/ fmul st, st
  5820. fmulp st, st1 (hp2) }
  5821. begin
  5822. RemoveCurrentP(p, hp1);
  5823. if (taicpu(hp2).opcode = A_FADDP) then
  5824. taicpu(hp2).opcode := A_FADD
  5825. else
  5826. taicpu(hp2).opcode := A_FMUL;
  5827. taicpu(hp2).oper[1]^.reg := NR_ST;
  5828. end
  5829. else
  5830. { change to
  5831. fld/fst mem1 (hp1) fld/fst mem1
  5832. fld mem1 (p) fld st}
  5833. begin
  5834. taicpu(p).changeopsize(S_FL);
  5835. taicpu(p).loadreg(0,NR_ST);
  5836. end
  5837. else
  5838. begin
  5839. case taicpu(hp2).opcode Of
  5840. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  5841. { change to
  5842. fld/fst mem1 (hp1) fld/fst mem1
  5843. fld mem2 (p) fxxx mem2
  5844. fxxxp st, st1 (hp2) }
  5845. begin
  5846. case taicpu(hp2).opcode Of
  5847. A_FADDP: taicpu(p).opcode := A_FADD;
  5848. A_FMULP: taicpu(p).opcode := A_FMUL;
  5849. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  5850. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  5851. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  5852. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  5853. else
  5854. internalerror(2019050533);
  5855. end;
  5856. RemoveInstruction(hp2);
  5857. end
  5858. else
  5859. ;
  5860. end
  5861. end
  5862. end;
  5863. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  5864. begin
  5865. Result := condition_in(cond1, cond2) or
  5866. { Not strictly subsets due to the actual flags checked, but because we're
  5867. comparing integers, E is a subset of AE and GE and their aliases }
  5868. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  5869. end;
  5870. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  5871. var
  5872. v: TCGInt;
  5873. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  5874. FirstMatch: Boolean;
  5875. NewReg: TRegister;
  5876. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  5877. begin
  5878. Result:=false;
  5879. { All these optimisations need a next instruction }
  5880. if not GetNextInstruction(p, hp1) then
  5881. Exit;
  5882. { Search for:
  5883. cmp ###,###
  5884. j(c1) @lbl1
  5885. ...
  5886. @lbl:
  5887. cmp ###.### (same comparison as above)
  5888. j(c2) @lbl2
  5889. If c1 is a subset of c2, change to:
  5890. cmp ###,###
  5891. j(c2) @lbl2
  5892. (@lbl1 may become a dead label as a result)
  5893. }
  5894. { Also handle cases where there are multiple jumps in a row }
  5895. p_jump := hp1;
  5896. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  5897. begin
  5898. if IsJumpToLabel(taicpu(p_jump)) then
  5899. begin
  5900. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  5901. p_label := nil;
  5902. if Assigned(JumpLabel) then
  5903. p_label := getlabelwithsym(JumpLabel);
  5904. if Assigned(p_label) and
  5905. GetNextInstruction(p_label, p_dist) and
  5906. MatchInstruction(p_dist, A_CMP, []) and
  5907. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  5908. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  5909. GetNextInstruction(p_dist, hp1_dist) and
  5910. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  5911. begin
  5912. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  5913. if JumpLabel = JumpLabel_dist then
  5914. { This is an infinite loop }
  5915. Exit;
  5916. { Best optimisation when the first condition is a subset (or equal) of the second }
  5917. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  5918. begin
  5919. { Any registers used here will already be allocated }
  5920. if Assigned(JumpLabel_dist) then
  5921. JumpLabel_dist.IncRefs;
  5922. if Assigned(JumpLabel) then
  5923. JumpLabel.DecRefs;
  5924. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  5925. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  5926. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  5927. Result := True;
  5928. { Don't exit yet. Since p and p_jump haven't actually been
  5929. removed, we can check for more on this iteration }
  5930. end
  5931. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  5932. GetNextInstruction(hp1_dist, hp1_label) and
  5933. SkipAligns(hp1_label, hp1_label) and
  5934. (hp1_label.typ = ait_label) then
  5935. begin
  5936. JumpLabel_far := tai_label(hp1_label).labsym;
  5937. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  5938. { This is an infinite loop }
  5939. Exit;
  5940. if Assigned(JumpLabel_far) then
  5941. begin
  5942. { In this situation, if the first jump branches, the second one will never,
  5943. branch so change the destination label to after the second jump }
  5944. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  5945. if Assigned(JumpLabel) then
  5946. JumpLabel.DecRefs;
  5947. JumpLabel_far.IncRefs;
  5948. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  5949. Result := True;
  5950. { Don't exit yet. Since p and p_jump haven't actually been
  5951. removed, we can check for more on this iteration }
  5952. Continue;
  5953. end;
  5954. end;
  5955. end;
  5956. end;
  5957. { Search for:
  5958. cmp ###,###
  5959. j(c1) @lbl1
  5960. cmp ###,### (same as first)
  5961. Remove second cmp
  5962. }
  5963. if GetNextInstruction(p_jump, hp2) and
  5964. (
  5965. (
  5966. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  5967. (
  5968. (
  5969. MatchOpType(taicpu(p), top_const, top_reg) and
  5970. MatchOpType(taicpu(hp2), top_const, top_reg) and
  5971. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  5972. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5973. ) or (
  5974. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  5975. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  5976. )
  5977. )
  5978. ) or (
  5979. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  5980. MatchOperand(taicpu(p).oper[0]^, 0) and
  5981. (taicpu(p).oper[1]^.typ = top_reg) and
  5982. MatchInstruction(hp2, A_TEST, []) and
  5983. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  5984. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  5985. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  5986. )
  5987. ) then
  5988. begin
  5989. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  5990. RemoveInstruction(hp2);
  5991. Result := True;
  5992. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  5993. end;
  5994. GetNextInstruction(p_jump, p_jump);
  5995. end;
  5996. {
  5997. Try to optimise the following:
  5998. cmp $x,### ($x and $y can be registers or constants)
  5999. je @lbl1 (only reference)
  6000. cmp $y,### (### are identical)
  6001. @Lbl:
  6002. sete %reg1
  6003. Change to:
  6004. cmp $x,###
  6005. sete %reg2 (allocate new %reg2)
  6006. cmp $y,###
  6007. sete %reg1
  6008. orb %reg2,%reg1
  6009. (dealloc %reg2)
  6010. This adds an instruction (so don't perform under -Os), but it removes
  6011. a conditional branch.
  6012. }
  6013. if not (cs_opt_size in current_settings.optimizerswitches) and
  6014. (
  6015. (hp1 = p_jump) or
  6016. GetNextInstruction(p, hp1)
  6017. ) and
  6018. MatchInstruction(hp1, A_Jcc, []) and
  6019. IsJumpToLabel(taicpu(hp1)) and
  6020. (taicpu(hp1).condition in [C_E, C_Z]) and
  6021. GetNextInstruction(hp1, hp2) and
  6022. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6023. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6024. { The first operand of CMP instructions can only be a register or
  6025. immediate anyway, so no need to check }
  6026. GetNextInstruction(hp2, p_label) and
  6027. (p_label.typ = ait_label) and
  6028. (tai_label(p_label).labsym.getrefs = 1) and
  6029. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6030. GetNextInstruction(p_label, p_dist) and
  6031. MatchInstruction(p_dist, A_SETcc, []) and
  6032. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6033. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  6034. begin
  6035. TransferUsedRegs(TmpUsedRegs);
  6036. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6037. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6038. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6039. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6040. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  6041. { Get the instruction after the SETcc instruction so we can
  6042. allocate a new register over the entire range }
  6043. GetNextInstruction(p_dist, hp1_dist) then
  6044. begin
  6045. { Register can appear in p if it's not used afterwards, so only
  6046. allocate between hp1 and hp1_dist }
  6047. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  6048. if NewReg <> NR_NO then
  6049. begin
  6050. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6051. { Change the jump instruction into a SETcc instruction }
  6052. taicpu(hp1).opcode := A_SETcc;
  6053. taicpu(hp1).opsize := S_B;
  6054. taicpu(hp1).loadreg(0, NewReg);
  6055. { This is now a dead label }
  6056. tai_label(p_label).labsym.decrefs;
  6057. { Prefer adding before the next instruction so the FLAGS
  6058. register is deallicated first }
  6059. AsmL.InsertBefore(
  6060. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  6061. hp1_dist
  6062. );
  6063. Result := True;
  6064. { Don't exit yet, as p wasn't changed and hp1, while
  6065. modified, is still intact and might be optimised by the
  6066. SETcc optimisation below }
  6067. end;
  6068. end;
  6069. end;
  6070. if taicpu(p).oper[0]^.typ = top_const then
  6071. begin
  6072. if (taicpu(p).oper[0]^.val = 0) and
  6073. (taicpu(p).oper[1]^.typ = top_reg) and
  6074. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6075. begin
  6076. hp2 := p;
  6077. FirstMatch := True;
  6078. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6079. anything meaningful once it's converted to "test %reg,%reg";
  6080. additionally, some jumps will always (or never) branch, so
  6081. evaluate every jump immediately following the
  6082. comparison, optimising the conditions if possible.
  6083. Similarly with SETcc... those that are always set to 0 or 1
  6084. are changed to MOV instructions }
  6085. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6086. (
  6087. GetNextInstruction(hp2, hp1) and
  6088. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6089. ) do
  6090. begin
  6091. FirstMatch := False;
  6092. case taicpu(hp1).condition of
  6093. C_B, C_C, C_NAE, C_O:
  6094. { For B/NAE:
  6095. Will never branch since an unsigned integer can never be below zero
  6096. For C/O:
  6097. Result cannot overflow because 0 is being subtracted
  6098. }
  6099. begin
  6100. if taicpu(hp1).opcode = A_Jcc then
  6101. begin
  6102. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6103. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6104. RemoveInstruction(hp1);
  6105. { Since hp1 was deleted, hp2 must not be updated }
  6106. Continue;
  6107. end
  6108. else
  6109. begin
  6110. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6111. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6112. taicpu(hp1).opcode := A_MOV;
  6113. taicpu(hp1).ops := 2;
  6114. taicpu(hp1).condition := C_None;
  6115. taicpu(hp1).opsize := S_B;
  6116. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6117. taicpu(hp1).loadconst(0, 0);
  6118. end;
  6119. end;
  6120. C_BE, C_NA:
  6121. begin
  6122. { Will only branch if equal to zero }
  6123. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6124. taicpu(hp1).condition := C_E;
  6125. end;
  6126. C_A, C_NBE:
  6127. begin
  6128. { Will only branch if not equal to zero }
  6129. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6130. taicpu(hp1).condition := C_NE;
  6131. end;
  6132. C_AE, C_NB, C_NC, C_NO:
  6133. begin
  6134. { Will always branch }
  6135. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6136. if taicpu(hp1).opcode = A_Jcc then
  6137. begin
  6138. MakeUnconditional(taicpu(hp1));
  6139. { Any jumps/set that follow will now be dead code }
  6140. RemoveDeadCodeAfterJump(taicpu(hp1));
  6141. Break;
  6142. end
  6143. else
  6144. begin
  6145. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6146. taicpu(hp1).opcode := A_MOV;
  6147. taicpu(hp1).ops := 2;
  6148. taicpu(hp1).condition := C_None;
  6149. taicpu(hp1).opsize := S_B;
  6150. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6151. taicpu(hp1).loadconst(0, 1);
  6152. end;
  6153. end;
  6154. C_None:
  6155. InternalError(2020012201);
  6156. C_P, C_PE, C_NP, C_PO:
  6157. { We can't handle parity checks and they should never be generated
  6158. after a general-purpose CMP (it's used in some floating-point
  6159. comparisons that don't use CMP) }
  6160. InternalError(2020012202);
  6161. else
  6162. { Zero/Equality, Sign, their complements and all of the
  6163. signed comparisons do not need to be converted };
  6164. end;
  6165. hp2 := hp1;
  6166. end;
  6167. { Convert the instruction to a TEST }
  6168. taicpu(p).opcode := A_TEST;
  6169. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6170. Result := True;
  6171. Exit;
  6172. end
  6173. else if (taicpu(p).oper[0]^.val = 1) and
  6174. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6175. (taicpu(hp1).condition in [C_L, C_NGE]) then
  6176. begin
  6177. { Convert; To:
  6178. cmp $1,r/m cmp $0,r/m
  6179. jl @lbl jle @lbl
  6180. }
  6181. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  6182. taicpu(p).oper[0]^.val := 0;
  6183. taicpu(hp1).condition := C_LE;
  6184. { If the instruction is now "cmp $0,%reg", convert it to a
  6185. TEST (and effectively do the work of the "cmp $0,%reg" in
  6186. the block above)
  6187. If it's a reference, we can get away with not setting
  6188. Result to True because he haven't evaluated the jump
  6189. in this pass yet.
  6190. }
  6191. if (taicpu(p).oper[1]^.typ = top_reg) then
  6192. begin
  6193. taicpu(p).opcode := A_TEST;
  6194. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6195. Result := True;
  6196. end;
  6197. Exit;
  6198. end
  6199. else if (taicpu(p).oper[1]^.typ = top_reg)
  6200. {$ifdef x86_64}
  6201. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6202. {$endif x86_64}
  6203. then
  6204. begin
  6205. { cmp register,$8000 neg register
  6206. je target --> jo target
  6207. .... only if register is deallocated before jump.}
  6208. case Taicpu(p).opsize of
  6209. S_B: v:=$80;
  6210. S_W: v:=$8000;
  6211. S_L: v:=qword($80000000);
  6212. else
  6213. internalerror(2013112905);
  6214. end;
  6215. if (taicpu(p).oper[0]^.val=v) and
  6216. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6217. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6218. begin
  6219. TransferUsedRegs(TmpUsedRegs);
  6220. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6221. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6222. begin
  6223. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6224. Taicpu(p).opcode:=A_NEG;
  6225. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6226. Taicpu(p).clearop(1);
  6227. Taicpu(p).ops:=1;
  6228. if Taicpu(hp1).condition=C_E then
  6229. Taicpu(hp1).condition:=C_O
  6230. else
  6231. Taicpu(hp1).condition:=C_NO;
  6232. Result:=true;
  6233. exit;
  6234. end;
  6235. end;
  6236. end;
  6237. end;
  6238. if TrySwapMovCmp(p, hp1) then
  6239. begin
  6240. Result := True;
  6241. Exit;
  6242. end;
  6243. end;
  6244. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6245. var
  6246. hp1: tai;
  6247. begin
  6248. {
  6249. remove the second (v)pxor from
  6250. pxor reg,reg
  6251. ...
  6252. pxor reg,reg
  6253. }
  6254. Result:=false;
  6255. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6256. MatchOpType(taicpu(p),top_reg,top_reg) and
  6257. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6258. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6259. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6260. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  6261. begin
  6262. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  6263. RemoveInstruction(hp1);
  6264. Result:=true;
  6265. Exit;
  6266. end
  6267. {
  6268. replace
  6269. pxor reg1,reg1
  6270. movapd/s reg1,reg2
  6271. dealloc reg1
  6272. by
  6273. pxor reg2,reg2
  6274. }
  6275. else if GetNextInstruction(p,hp1) and
  6276. { we mix single and double opperations here because we assume that the compiler
  6277. generates vmovapd only after double operations and vmovaps only after single operations }
  6278. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  6279. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  6280. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  6281. (taicpu(p).oper[0]^.typ=top_reg) then
  6282. begin
  6283. TransferUsedRegs(TmpUsedRegs);
  6284. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6285. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  6286. begin
  6287. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  6288. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  6289. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  6290. RemoveInstruction(hp1);
  6291. result:=true;
  6292. end;
  6293. end;
  6294. end;
  6295. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  6296. var
  6297. hp1: tai;
  6298. begin
  6299. {
  6300. remove the second (v)pxor from
  6301. (v)pxor reg,reg
  6302. ...
  6303. (v)pxor reg,reg
  6304. }
  6305. Result:=false;
  6306. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  6307. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6308. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  6309. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  6310. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6311. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  6312. begin
  6313. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  6314. RemoveInstruction(hp1);
  6315. Result:=true;
  6316. Exit;
  6317. end
  6318. else
  6319. Result:=OptPass1VOP(p);
  6320. end;
  6321. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  6322. var
  6323. hp1 : tai;
  6324. begin
  6325. result:=false;
  6326. { replace
  6327. IMul const,%mreg1,%mreg2
  6328. Mov %reg2,%mreg3
  6329. dealloc %mreg3
  6330. by
  6331. Imul const,%mreg1,%mreg23
  6332. }
  6333. if (taicpu(p).ops=3) and
  6334. GetNextInstruction(p,hp1) and
  6335. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6336. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6337. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6338. begin
  6339. TransferUsedRegs(TmpUsedRegs);
  6340. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6341. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6342. begin
  6343. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6344. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  6345. RemoveInstruction(hp1);
  6346. result:=true;
  6347. end;
  6348. end;
  6349. end;
  6350. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  6351. var
  6352. hp1 : tai;
  6353. begin
  6354. result:=false;
  6355. { replace
  6356. IMul %reg0,%reg1,%reg2
  6357. Mov %reg2,%reg3
  6358. dealloc %reg2
  6359. by
  6360. Imul %reg0,%reg1,%reg3
  6361. }
  6362. if GetNextInstruction(p,hp1) and
  6363. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  6364. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  6365. (taicpu(hp1).oper[1]^.typ=top_reg) then
  6366. begin
  6367. TransferUsedRegs(TmpUsedRegs);
  6368. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6369. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  6370. begin
  6371. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  6372. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  6373. RemoveInstruction(hp1);
  6374. result:=true;
  6375. end;
  6376. end;
  6377. end;
  6378. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  6379. var
  6380. hp1: tai;
  6381. begin
  6382. Result:=false;
  6383. { get rid of
  6384. (v)cvtss2sd reg0,<reg1,>reg2
  6385. (v)cvtss2sd reg2,<reg2,>reg0
  6386. }
  6387. if GetNextInstruction(p,hp1) and
  6388. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  6389. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  6390. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  6391. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  6392. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  6393. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  6394. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  6395. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  6396. )
  6397. ) then
  6398. begin
  6399. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  6400. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  6401. begin
  6402. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  6403. RemoveCurrentP(p);
  6404. RemoveInstruction(hp1);
  6405. end
  6406. else
  6407. begin
  6408. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  6409. if taicpu(hp1).opcode=A_CVTSD2SS then
  6410. begin
  6411. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  6412. taicpu(p).opcode:=A_MOVAPS;
  6413. end
  6414. else
  6415. begin
  6416. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  6417. taicpu(p).opcode:=A_VMOVAPS;
  6418. end;
  6419. taicpu(p).ops:=2;
  6420. RemoveInstruction(hp1);
  6421. end;
  6422. Result:=true;
  6423. Exit;
  6424. end;
  6425. end;
  6426. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  6427. var
  6428. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  6429. ThisReg: TRegister;
  6430. begin
  6431. Result := False;
  6432. if not GetNextInstruction(p,hp1) then
  6433. Exit;
  6434. {
  6435. convert
  6436. j<c> .L1
  6437. mov 1,reg
  6438. jmp .L2
  6439. .L1
  6440. mov 0,reg
  6441. .L2
  6442. into
  6443. mov 0,reg
  6444. set<not(c)> reg
  6445. take care of alignment and that the mov 0,reg is not converted into a xor as this
  6446. would destroy the flag contents
  6447. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  6448. executed at the same time as a previous comparison.
  6449. set<not(c)> reg
  6450. movzx reg, reg
  6451. }
  6452. if MatchInstruction(hp1,A_MOV,[]) and
  6453. (taicpu(hp1).oper[0]^.typ = top_const) and
  6454. (
  6455. (
  6456. (taicpu(hp1).oper[1]^.typ = top_reg)
  6457. {$ifdef i386}
  6458. { Under i386, ESI, EDI, EBP and ESP
  6459. don't have an 8-bit representation }
  6460. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  6461. {$endif i386}
  6462. ) or (
  6463. {$ifdef i386}
  6464. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  6465. {$endif i386}
  6466. (taicpu(hp1).opsize = S_B)
  6467. )
  6468. ) and
  6469. GetNextInstruction(hp1,hp2) and
  6470. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  6471. GetNextInstruction(hp2,hp3) and
  6472. SkipAligns(hp3, hp3) and
  6473. (hp3.typ=ait_label) and
  6474. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  6475. GetNextInstruction(hp3,hp4) and
  6476. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  6477. (taicpu(hp4).oper[0]^.typ = top_const) and
  6478. (
  6479. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  6480. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  6481. ) and
  6482. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  6483. GetNextInstruction(hp4,hp5) and
  6484. SkipAligns(hp5, hp5) and
  6485. (hp5.typ=ait_label) and
  6486. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  6487. begin
  6488. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6489. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  6490. tai_label(hp3).labsym.DecRefs;
  6491. { If this isn't the only reference to the middle label, we can
  6492. still make a saving - only that the first jump and everything
  6493. that follows will remain. }
  6494. if (tai_label(hp3).labsym.getrefs = 0) then
  6495. begin
  6496. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6497. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  6498. else
  6499. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  6500. { remove jump, first label and second MOV (also catching any aligns) }
  6501. repeat
  6502. if not GetNextInstruction(hp2, hp3) then
  6503. InternalError(2021040810);
  6504. RemoveInstruction(hp2);
  6505. hp2 := hp3;
  6506. until hp2 = hp5;
  6507. { Don't decrement reference count before the removal loop
  6508. above, otherwise GetNextInstruction won't stop on the
  6509. the label }
  6510. tai_label(hp5).labsym.DecRefs;
  6511. end
  6512. else
  6513. begin
  6514. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  6515. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  6516. else
  6517. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  6518. end;
  6519. taicpu(p).opcode:=A_SETcc;
  6520. taicpu(p).opsize:=S_B;
  6521. taicpu(p).is_jmp:=False;
  6522. if taicpu(hp1).opsize=S_B then
  6523. begin
  6524. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6525. if taicpu(hp1).oper[1]^.typ = top_reg then
  6526. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  6527. RemoveInstruction(hp1);
  6528. end
  6529. else
  6530. begin
  6531. { Will be a register because the size can't be S_B otherwise }
  6532. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  6533. taicpu(p).loadreg(0, ThisReg);
  6534. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  6535. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  6536. begin
  6537. case taicpu(hp1).opsize of
  6538. S_W:
  6539. taicpu(hp1).opsize := S_BW;
  6540. S_L:
  6541. taicpu(hp1).opsize := S_BL;
  6542. {$ifdef x86_64}
  6543. S_Q:
  6544. begin
  6545. taicpu(hp1).opsize := S_BL;
  6546. { Change the destination register to 32-bit }
  6547. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  6548. end;
  6549. {$endif x86_64}
  6550. else
  6551. InternalError(2021040820);
  6552. end;
  6553. taicpu(hp1).opcode := A_MOVZX;
  6554. taicpu(hp1).loadreg(0, ThisReg);
  6555. end
  6556. else
  6557. begin
  6558. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  6559. { hp1 is already a MOV instruction with the correct register }
  6560. taicpu(hp1).loadconst(0, 0);
  6561. { Inserting it right before p will guarantee that the flags are also tracked }
  6562. asml.Remove(hp1);
  6563. asml.InsertBefore(hp1, p);
  6564. end;
  6565. end;
  6566. Result:=true;
  6567. exit;
  6568. end
  6569. else if (hp1.typ = ait_label) then
  6570. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  6571. end;
  6572. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  6573. var
  6574. hp1, hp2, hp3: tai;
  6575. SourceRef, TargetRef: TReference;
  6576. CurrentReg: TRegister;
  6577. begin
  6578. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  6579. if not UseAVX then
  6580. InternalError(2021100501);
  6581. Result := False;
  6582. { Look for the following to simplify:
  6583. vmovdqa/u x(mem1), %xmmreg
  6584. vmovdqa/u %xmmreg, y(mem2)
  6585. vmovdqa/u x+16(mem1), %xmmreg
  6586. vmovdqa/u %xmmreg, y+16(mem2)
  6587. Change to:
  6588. vmovdqa/u x(mem1), %ymmreg
  6589. vmovdqa/u %ymmreg, y(mem2)
  6590. vpxor %ymmreg, %ymmreg, %ymmreg
  6591. ( The VPXOR instruction is to zero the upper half, thus removing the
  6592. need to call the potentially expensive VZEROUPPER instruction. Other
  6593. peephole optimisations can remove VPXOR if it's unnecessary )
  6594. }
  6595. TransferUsedRegs(TmpUsedRegs);
  6596. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6597. { NOTE: In the optimisations below, if the references dictate that an
  6598. aligned move is possible (i.e. VMOVDQA), the existing instructions
  6599. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  6600. if (taicpu(p).opsize = S_XMM) and
  6601. MatchOpType(taicpu(p), top_ref, top_reg) and
  6602. GetNextInstruction(p, hp1) and
  6603. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6604. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  6605. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  6606. begin
  6607. SourceRef := taicpu(p).oper[0]^.ref^;
  6608. TargetRef := taicpu(hp1).oper[1]^.ref^;
  6609. if GetNextInstruction(hp1, hp2) and
  6610. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6611. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  6612. begin
  6613. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  6614. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6615. Inc(SourceRef.offset, 16);
  6616. { Reuse the register in the first block move }
  6617. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  6618. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6619. begin
  6620. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6621. Inc(TargetRef.offset, 16);
  6622. if GetNextInstruction(hp2, hp3) and
  6623. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  6624. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6625. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6626. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6627. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6628. begin
  6629. { Update the register tracking to the new size }
  6630. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  6631. { Remember that the offsets are 16 ahead }
  6632. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6633. if not (
  6634. ((SourceRef.offset mod 32) = 16) and
  6635. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6636. ) then
  6637. taicpu(p).opcode := A_VMOVDQU;
  6638. taicpu(p).opsize := S_YMM;
  6639. taicpu(p).oper[1]^.reg := CurrentReg;
  6640. if not (
  6641. ((TargetRef.offset mod 32) = 16) and
  6642. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6643. ) then
  6644. taicpu(hp1).opcode := A_VMOVDQU;
  6645. taicpu(hp1).opsize := S_YMM;
  6646. taicpu(hp1).oper[0]^.reg := CurrentReg;
  6647. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  6648. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6649. if (pi_uses_ymm in current_procinfo.flags) then
  6650. RemoveInstruction(hp2)
  6651. else
  6652. begin
  6653. taicpu(hp2).opcode := A_VPXOR;
  6654. taicpu(hp2).opsize := S_YMM;
  6655. taicpu(hp2).loadreg(0, CurrentReg);
  6656. taicpu(hp2).loadreg(1, CurrentReg);
  6657. taicpu(hp2).loadreg(2, CurrentReg);
  6658. taicpu(hp2).ops := 3;
  6659. end;
  6660. RemoveInstruction(hp3);
  6661. Result := True;
  6662. Exit;
  6663. end;
  6664. end
  6665. else
  6666. begin
  6667. { See if the next references are 16 less rather than 16 greater }
  6668. Dec(SourceRef.offset, 32); { -16 the other way }
  6669. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  6670. begin
  6671. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6672. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  6673. if GetNextInstruction(hp2, hp3) and
  6674. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  6675. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  6676. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  6677. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  6678. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  6679. begin
  6680. { Update the register tracking to the new size }
  6681. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  6682. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  6683. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  6684. if not(
  6685. ((SourceRef.offset mod 32) = 0) and
  6686. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  6687. ) then
  6688. taicpu(hp2).opcode := A_VMOVDQU;
  6689. taicpu(hp2).opsize := S_YMM;
  6690. taicpu(hp2).oper[1]^.reg := CurrentReg;
  6691. if not (
  6692. ((TargetRef.offset mod 32) = 0) and
  6693. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  6694. ) then
  6695. taicpu(hp3).opcode := A_VMOVDQU;
  6696. taicpu(hp3).opsize := S_YMM;
  6697. taicpu(hp3).oper[0]^.reg := CurrentReg;
  6698. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  6699. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  6700. if (pi_uses_ymm in current_procinfo.flags) then
  6701. RemoveInstruction(hp1)
  6702. else
  6703. begin
  6704. taicpu(hp1).opcode := A_VPXOR;
  6705. taicpu(hp1).opsize := S_YMM;
  6706. taicpu(hp1).loadreg(0, CurrentReg);
  6707. taicpu(hp1).loadreg(1, CurrentReg);
  6708. taicpu(hp1).loadreg(2, CurrentReg);
  6709. taicpu(hp1).ops := 3;
  6710. Asml.Remove(hp1);
  6711. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  6712. end;
  6713. RemoveCurrentP(p, hp2);
  6714. Result := True;
  6715. Exit;
  6716. end;
  6717. end;
  6718. end;
  6719. end;
  6720. end;
  6721. end;
  6722. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  6723. var
  6724. hp2, hp3, first_assignment: tai;
  6725. IncCount, OperIdx: Integer;
  6726. OrigLabel: TAsmLabel;
  6727. begin
  6728. Count := 0;
  6729. Result := False;
  6730. first_assignment := nil;
  6731. if (LoopCount >= 20) then
  6732. begin
  6733. { Guard against infinite loops }
  6734. Exit;
  6735. end;
  6736. if (taicpu(p).oper[0]^.typ <> top_ref) or
  6737. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  6738. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  6739. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  6740. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  6741. Exit;
  6742. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  6743. {
  6744. change
  6745. jmp .L1
  6746. ...
  6747. .L1:
  6748. mov ##, ## ( multiple movs possible )
  6749. jmp/ret
  6750. into
  6751. mov ##, ##
  6752. jmp/ret
  6753. }
  6754. if not Assigned(hp1) then
  6755. begin
  6756. hp1 := GetLabelWithSym(OrigLabel);
  6757. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  6758. Exit;
  6759. end;
  6760. hp2 := hp1;
  6761. while Assigned(hp2) do
  6762. begin
  6763. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  6764. SkipLabels(hp2,hp2);
  6765. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  6766. Break;
  6767. case taicpu(hp2).opcode of
  6768. A_MOVSS:
  6769. begin
  6770. if taicpu(hp2).ops = 0 then
  6771. { Wrong MOVSS }
  6772. Break;
  6773. Inc(Count);
  6774. if Count >= 5 then
  6775. { Too many to be worthwhile }
  6776. Break;
  6777. GetNextInstruction(hp2, hp2);
  6778. Continue;
  6779. end;
  6780. A_MOV,
  6781. A_MOVD,
  6782. A_MOVQ,
  6783. A_MOVSX,
  6784. {$ifdef x86_64}
  6785. A_MOVSXD,
  6786. {$endif x86_64}
  6787. A_MOVZX,
  6788. A_MOVAPS,
  6789. A_MOVUPS,
  6790. A_MOVSD,
  6791. A_MOVAPD,
  6792. A_MOVUPD,
  6793. A_MOVDQA,
  6794. A_MOVDQU,
  6795. A_VMOVSS,
  6796. A_VMOVAPS,
  6797. A_VMOVUPS,
  6798. A_VMOVSD,
  6799. A_VMOVAPD,
  6800. A_VMOVUPD,
  6801. A_VMOVDQA,
  6802. A_VMOVDQU:
  6803. begin
  6804. Inc(Count);
  6805. if Count >= 5 then
  6806. { Too many to be worthwhile }
  6807. Break;
  6808. GetNextInstruction(hp2, hp2);
  6809. Continue;
  6810. end;
  6811. A_JMP:
  6812. begin
  6813. { Guard against infinite loops }
  6814. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  6815. Exit;
  6816. { Analyse this jump first in case it also duplicates assignments }
  6817. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  6818. begin
  6819. { Something did change! }
  6820. Result := True;
  6821. Inc(Count, IncCount);
  6822. if Count >= 5 then
  6823. begin
  6824. { Too many to be worthwhile }
  6825. Exit;
  6826. end;
  6827. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  6828. Break;
  6829. end;
  6830. Result := True;
  6831. Break;
  6832. end;
  6833. A_RET:
  6834. begin
  6835. Result := True;
  6836. Break;
  6837. end;
  6838. else
  6839. Break;
  6840. end;
  6841. end;
  6842. if Result then
  6843. begin
  6844. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  6845. if Count = 0 then
  6846. begin
  6847. Result := False;
  6848. Exit;
  6849. end;
  6850. hp3 := p;
  6851. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  6852. while True do
  6853. begin
  6854. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  6855. SkipLabels(hp1,hp1);
  6856. if (hp1.typ <> ait_instruction) then
  6857. InternalError(2021040720);
  6858. case taicpu(hp1).opcode of
  6859. A_JMP:
  6860. begin
  6861. { Change the original jump to the new destination }
  6862. OrigLabel.decrefs;
  6863. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  6864. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  6865. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6866. if not Assigned(first_assignment) then
  6867. InternalError(2021040810)
  6868. else
  6869. p := first_assignment;
  6870. Exit;
  6871. end;
  6872. A_RET:
  6873. begin
  6874. { Now change the jump into a RET instruction }
  6875. ConvertJumpToRET(p, hp1);
  6876. { Set p to the first duplicated assignment so it can get optimised if needs be }
  6877. if not Assigned(first_assignment) then
  6878. InternalError(2021040811)
  6879. else
  6880. p := first_assignment;
  6881. Exit;
  6882. end;
  6883. else
  6884. begin
  6885. { Duplicate the MOV instruction }
  6886. hp3:=tai(hp1.getcopy);
  6887. if first_assignment = nil then
  6888. first_assignment := hp3;
  6889. asml.InsertBefore(hp3, p);
  6890. { Make sure the compiler knows about any final registers written here }
  6891. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  6892. with taicpu(hp3).oper[OperIdx]^ do
  6893. begin
  6894. case typ of
  6895. top_ref:
  6896. begin
  6897. if (ref^.base <> NR_NO) and
  6898. (getsupreg(ref^.base) <> RS_ESP) and
  6899. (getsupreg(ref^.base) <> RS_EBP)
  6900. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  6901. then
  6902. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  6903. if (ref^.index <> NR_NO) and
  6904. (getsupreg(ref^.index) <> RS_ESP) and
  6905. (getsupreg(ref^.index) <> RS_EBP)
  6906. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  6907. (ref^.index <> ref^.base) then
  6908. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  6909. end;
  6910. top_reg:
  6911. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  6912. else
  6913. ;
  6914. end;
  6915. end;
  6916. end;
  6917. end;
  6918. if not GetNextInstruction(hp1, hp1) then
  6919. { Should have dropped out earlier }
  6920. InternalError(2021040710);
  6921. end;
  6922. end;
  6923. end;
  6924. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  6925. var
  6926. hp2: tai;
  6927. X: Integer;
  6928. const
  6929. WriteOp: array[0..3] of set of TInsChange = (
  6930. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  6931. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  6932. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  6933. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  6934. RegWriteFlags: array[0..7] of set of TInsChange = (
  6935. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  6936. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  6937. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  6938. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  6939. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  6940. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  6941. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  6942. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  6943. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  6944. begin
  6945. { If we have something like:
  6946. cmp ###,%reg1
  6947. mov 0,%reg2
  6948. And no modified registers are shared, move the instruction to before
  6949. the comparison as this means it can be optimised without worrying
  6950. about the FLAGS register. (CMP/MOV is generated by
  6951. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  6952. As long as the second instruction doesn't use the flags or one of the
  6953. registers used by CMP or TEST (also check any references that use the
  6954. registers), then it can be moved prior to the comparison.
  6955. }
  6956. Result := False;
  6957. if (hp1.typ <> ait_instruction) or
  6958. taicpu(hp1).is_jmp or
  6959. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  6960. Exit;
  6961. { NOP is a pipeline fence, likely marking the beginning of the function
  6962. epilogue, so drop out. Similarly, drop out if POP or RET are
  6963. encountered }
  6964. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  6965. Exit;
  6966. if (taicpu(hp1).opcode = A_MOVSS) and
  6967. (taicpu(hp1).ops = 0) then
  6968. { Wrong MOVSS }
  6969. Exit;
  6970. { Check for writes to specific registers first }
  6971. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  6972. for X := 0 to 7 do
  6973. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  6974. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  6975. Exit;
  6976. for X := 0 to taicpu(hp1).ops - 1 do
  6977. begin
  6978. { Check to see if this operand writes to something }
  6979. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  6980. { And matches something in the CMP/TEST instruction }
  6981. (
  6982. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  6983. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  6984. (
  6985. { If it's a register, make sure the register written to doesn't
  6986. appear in the cmp instruction as part of a reference }
  6987. (taicpu(hp1).oper[X]^.typ = top_reg) and
  6988. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  6989. )
  6990. ) then
  6991. Exit;
  6992. end;
  6993. { The instruction can be safely moved }
  6994. asml.Remove(hp1);
  6995. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  6996. if not GetLastInstruction(p, hp2) then
  6997. asml.InsertBefore(hp1, p)
  6998. else
  6999. asml.InsertAfter(hp1, hp2);
  7000. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7001. for X := 0 to taicpu(hp1).ops - 1 do
  7002. case taicpu(hp1).oper[X]^.typ of
  7003. top_reg:
  7004. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7005. top_ref:
  7006. begin
  7007. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7008. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7009. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7010. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7011. end;
  7012. else
  7013. ;
  7014. end;
  7015. if taicpu(hp1).opcode = A_LEA then
  7016. { The flags will be overwritten by the CMP/TEST instruction }
  7017. ConvertLEA(taicpu(hp1));
  7018. Result := True;
  7019. end;
  7020. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7021. function IsXCHGAcceptable: Boolean; inline;
  7022. begin
  7023. { Always accept if optimising for size }
  7024. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7025. (
  7026. {$ifdef x86_64}
  7027. { XCHG takes 3 cycles on AMD Athlon64 }
  7028. (current_settings.optimizecputype >= cpu_core_i)
  7029. {$else x86_64}
  7030. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7031. than 3, so it becomes a saving compared to three MOVs with two of
  7032. them able to execute simultaneously. [Kit] }
  7033. (current_settings.optimizecputype >= cpu_PentiumM)
  7034. {$endif x86_64}
  7035. );
  7036. end;
  7037. var
  7038. NewRef: TReference;
  7039. hp1, hp2, hp3, hp4: Tai;
  7040. {$ifndef x86_64}
  7041. OperIdx: Integer;
  7042. {$endif x86_64}
  7043. NewInstr : Taicpu;
  7044. NewAligh : Tai_align;
  7045. DestLabel: TAsmLabel;
  7046. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7047. var
  7048. NextInstr: tai;
  7049. begin
  7050. Result := False;
  7051. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7052. if not GetNextInstruction(InputInstr, NextInstr) or
  7053. (
  7054. { The FLAGS register isn't always tracked properly, so do not
  7055. perform this optimisation if a conditional statement follows }
  7056. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7057. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7058. ) then
  7059. begin
  7060. reference_reset(NewRef, 1, []);
  7061. NewRef.base := taicpu(p).oper[0]^.reg;
  7062. NewRef.scalefactor := 1;
  7063. if taicpu(InputInstr).opcode = A_ADD then
  7064. begin
  7065. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7066. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7067. end
  7068. else
  7069. begin
  7070. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7071. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7072. end;
  7073. taicpu(p).opcode := A_LEA;
  7074. taicpu(p).loadref(0, NewRef);
  7075. RemoveInstruction(InputInstr);
  7076. Result := True;
  7077. end;
  7078. end;
  7079. begin
  7080. Result:=false;
  7081. { This optimisation adds an instruction, so only do it for speed }
  7082. if not (cs_opt_size in current_settings.optimizerswitches) and
  7083. MatchOpType(taicpu(p), top_const, top_reg) and
  7084. (taicpu(p).oper[0]^.val = 0) then
  7085. begin
  7086. { To avoid compiler warning }
  7087. DestLabel := nil;
  7088. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7089. InternalError(2021040750);
  7090. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7091. Exit;
  7092. case hp1.typ of
  7093. ait_label:
  7094. begin
  7095. { Change:
  7096. mov $0,%reg mov $0,%reg
  7097. @Lbl1: @Lbl1:
  7098. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7099. je @Lbl2 jne @Lbl2
  7100. To: To:
  7101. mov $0,%reg mov $0,%reg
  7102. jmp @Lbl2 jmp @Lbl3
  7103. (align) (align)
  7104. @Lbl1: @Lbl1:
  7105. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  7106. je @Lbl2 je @Lbl2
  7107. @Lbl3: <-- Only if label exists
  7108. (Not if it's optimised for size)
  7109. }
  7110. if not GetNextInstruction(hp1, hp2) then
  7111. Exit;
  7112. if not (cs_opt_size in current_settings.optimizerswitches) and
  7113. (hp2.typ = ait_instruction) and
  7114. (
  7115. { Register sizes must exactly match }
  7116. (
  7117. (taicpu(hp2).opcode = A_CMP) and
  7118. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  7119. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7120. ) or (
  7121. (taicpu(hp2).opcode = A_TEST) and
  7122. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7123. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7124. )
  7125. ) and GetNextInstruction(hp2, hp3) and
  7126. (hp3.typ = ait_instruction) and
  7127. (taicpu(hp3).opcode = A_JCC) and
  7128. (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
  7129. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  7130. begin
  7131. { Check condition of jump }
  7132. { Always true? }
  7133. if condition_in(C_E, taicpu(hp3).condition) then
  7134. begin
  7135. { Copy label symbol and obtain matching label entry for the
  7136. conditional jump, as this will be our destination}
  7137. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  7138. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  7139. Result := True;
  7140. end
  7141. { Always false? }
  7142. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  7143. begin
  7144. { This is only worth it if there's a jump to take }
  7145. case hp2.typ of
  7146. ait_instruction:
  7147. begin
  7148. if taicpu(hp2).opcode = A_JMP then
  7149. begin
  7150. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7151. { An unconditional jump follows the conditional jump which will always be false,
  7152. so use this jump's destination for the new jump }
  7153. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  7154. Result := True;
  7155. end
  7156. else if taicpu(hp2).opcode = A_JCC then
  7157. begin
  7158. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7159. if condition_in(C_E, taicpu(hp2).condition) then
  7160. begin
  7161. { A second conditional jump follows the conditional jump which will always be false,
  7162. while the second jump is always True, so use this jump's destination for the new jump }
  7163. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  7164. Result := True;
  7165. end;
  7166. { Don't risk it if the jump isn't always true (Result remains False) }
  7167. end;
  7168. end;
  7169. else
  7170. { If anything else don't optimise };
  7171. end;
  7172. end;
  7173. if Result then
  7174. begin
  7175. { Just so we have something to insert as a paremeter}
  7176. reference_reset(NewRef, 1, []);
  7177. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  7178. { Now actually load the correct parameter }
  7179. NewInstr.loadsymbol(0, DestLabel, 0);
  7180. { Get instruction before original label (may not be p under -O3) }
  7181. if not GetLastInstruction(hp1, hp2) then
  7182. { Shouldn't fail here }
  7183. InternalError(2021040701);
  7184. DestLabel.increfs;
  7185. AsmL.InsertAfter(NewInstr, hp2);
  7186. { Add new alignment field }
  7187. (* AsmL.InsertAfter(
  7188. cai_align.create_max(
  7189. current_settings.alignment.jumpalign,
  7190. current_settings.alignment.jumpalignskipmax
  7191. ),
  7192. NewInstr
  7193. ); *)
  7194. end;
  7195. Exit;
  7196. end;
  7197. end;
  7198. else
  7199. ;
  7200. end;
  7201. end;
  7202. if not GetNextInstruction(p, hp1) then
  7203. Exit;
  7204. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  7205. and DoMovCmpMemOpt(p, hp1, True) then
  7206. begin
  7207. Result := True;
  7208. Exit;
  7209. end
  7210. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  7211. begin
  7212. { Sometimes the MOVs that OptPass2JMP produces can be improved
  7213. further, but we can't just put this jump optimisation in pass 1
  7214. because it tends to perform worse when conditional jumps are
  7215. nearby (e.g. when converting CMOV instructions). [Kit] }
  7216. if OptPass2JMP(hp1) then
  7217. { call OptPass1MOV once to potentially merge any MOVs that were created }
  7218. Result := OptPass1MOV(p)
  7219. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  7220. returned True and the instruction is still a MOV, thus checking
  7221. the optimisations below }
  7222. { If OptPass2JMP returned False, no optimisations were done to
  7223. the jump and there are no further optimisations that can be done
  7224. to the MOV instruction on this pass }
  7225. end
  7226. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7227. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  7228. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7229. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7230. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7231. begin
  7232. { Change:
  7233. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  7234. addl/q $x,%reg2 subl/q $x,%reg2
  7235. To:
  7236. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  7237. }
  7238. if (taicpu(hp1).oper[0]^.typ = top_const) and
  7239. { be lazy, checking separately for sub would be slightly better }
  7240. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  7241. begin
  7242. TransferUsedRegs(TmpUsedRegs);
  7243. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7244. if TryMovArith2Lea(hp1) then
  7245. begin
  7246. Result := True;
  7247. Exit;
  7248. end
  7249. end
  7250. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  7251. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  7252. { Same as above, but also adds or subtracts to %reg2 in between.
  7253. It's still valid as long as the flags aren't in use }
  7254. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  7255. MatchOpType(taicpu(hp2), top_const, top_reg) and
  7256. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  7257. { be lazy, checking separately for sub would be slightly better }
  7258. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  7259. begin
  7260. TransferUsedRegs(TmpUsedRegs);
  7261. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7262. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7263. if TryMovArith2Lea(hp2) then
  7264. begin
  7265. Result := True;
  7266. Exit;
  7267. end;
  7268. end;
  7269. end
  7270. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7271. {$ifdef x86_64}
  7272. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  7273. {$else x86_64}
  7274. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  7275. {$endif x86_64}
  7276. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7277. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  7278. { mov reg1, reg2 mov reg1, reg2
  7279. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  7280. begin
  7281. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  7282. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  7283. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  7284. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  7285. TransferUsedRegs(TmpUsedRegs);
  7286. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7287. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  7288. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  7289. then
  7290. begin
  7291. RemoveCurrentP(p, hp1);
  7292. Result:=true;
  7293. end;
  7294. exit;
  7295. end
  7296. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7297. IsXCHGAcceptable and
  7298. { XCHG doesn't support 8-byte registers }
  7299. (taicpu(p).opsize <> S_B) and
  7300. MatchInstruction(hp1, A_MOV, []) and
  7301. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7302. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  7303. GetNextInstruction(hp1, hp2) and
  7304. MatchInstruction(hp2, A_MOV, []) and
  7305. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  7306. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7307. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  7308. begin
  7309. { mov %reg1,%reg2
  7310. mov %reg3,%reg1 -> xchg %reg3,%reg1
  7311. mov %reg2,%reg3
  7312. (%reg2 not used afterwards)
  7313. Note that xchg takes 3 cycles to execute, and generally mov's take
  7314. only one cycle apiece, but the first two mov's can be executed in
  7315. parallel, only taking 2 cycles overall. Older processors should
  7316. therefore only optimise for size. [Kit]
  7317. }
  7318. TransferUsedRegs(TmpUsedRegs);
  7319. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7320. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7321. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  7322. begin
  7323. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  7324. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  7325. taicpu(hp1).opcode := A_XCHG;
  7326. RemoveCurrentP(p, hp1);
  7327. RemoveInstruction(hp2);
  7328. Result := True;
  7329. Exit;
  7330. end;
  7331. end
  7332. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  7333. MatchInstruction(hp1, A_SAR, []) then
  7334. begin
  7335. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  7336. begin
  7337. { the use of %edx also covers the opsize being S_L }
  7338. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  7339. begin
  7340. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  7341. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  7342. (taicpu(p).oper[1]^.reg = NR_EDX) then
  7343. begin
  7344. { Change:
  7345. movl %eax,%edx
  7346. sarl $31,%edx
  7347. To:
  7348. cltd
  7349. }
  7350. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  7351. RemoveInstruction(hp1);
  7352. taicpu(p).opcode := A_CDQ;
  7353. taicpu(p).opsize := S_NO;
  7354. taicpu(p).clearop(1);
  7355. taicpu(p).clearop(0);
  7356. taicpu(p).ops:=0;
  7357. Result := True;
  7358. end
  7359. else if (cs_opt_size in current_settings.optimizerswitches) and
  7360. (taicpu(p).oper[0]^.reg = NR_EDX) and
  7361. (taicpu(p).oper[1]^.reg = NR_EAX) then
  7362. begin
  7363. { Change:
  7364. movl %edx,%eax
  7365. sarl $31,%edx
  7366. To:
  7367. movl %edx,%eax
  7368. cltd
  7369. Note that this creates a dependency between the two instructions,
  7370. so only perform if optimising for size.
  7371. }
  7372. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  7373. taicpu(hp1).opcode := A_CDQ;
  7374. taicpu(hp1).opsize := S_NO;
  7375. taicpu(hp1).clearop(1);
  7376. taicpu(hp1).clearop(0);
  7377. taicpu(hp1).ops:=0;
  7378. end;
  7379. {$ifndef x86_64}
  7380. end
  7381. { Don't bother if CMOV is supported, because a more optimal
  7382. sequence would have been generated for the Abs() intrinsic }
  7383. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  7384. { the use of %eax also covers the opsize being S_L }
  7385. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  7386. (taicpu(p).oper[0]^.reg = NR_EAX) and
  7387. (taicpu(p).oper[1]^.reg = NR_EDX) and
  7388. GetNextInstruction(hp1, hp2) and
  7389. MatchInstruction(hp2, A_XOR, [S_L]) and
  7390. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  7391. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  7392. GetNextInstruction(hp2, hp3) and
  7393. MatchInstruction(hp3, A_SUB, [S_L]) and
  7394. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  7395. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  7396. begin
  7397. { Change:
  7398. movl %eax,%edx
  7399. sarl $31,%eax
  7400. xorl %eax,%edx
  7401. subl %eax,%edx
  7402. (Instruction that uses %edx)
  7403. (%eax deallocated)
  7404. (%edx deallocated)
  7405. To:
  7406. cltd
  7407. xorl %edx,%eax <-- Note the registers have swapped
  7408. subl %edx,%eax
  7409. (Instruction that uses %eax) <-- %eax rather than %edx
  7410. }
  7411. TransferUsedRegs(TmpUsedRegs);
  7412. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7413. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7414. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7415. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  7416. begin
  7417. if GetNextInstruction(hp3, hp4) and
  7418. not RegModifiedByInstruction(NR_EDX, hp4) and
  7419. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  7420. begin
  7421. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  7422. taicpu(p).opcode := A_CDQ;
  7423. taicpu(p).clearop(1);
  7424. taicpu(p).clearop(0);
  7425. taicpu(p).ops:=0;
  7426. RemoveInstruction(hp1);
  7427. taicpu(hp2).loadreg(0, NR_EDX);
  7428. taicpu(hp2).loadreg(1, NR_EAX);
  7429. taicpu(hp3).loadreg(0, NR_EDX);
  7430. taicpu(hp3).loadreg(1, NR_EAX);
  7431. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  7432. { Convert references in the following instruction (hp4) from %edx to %eax }
  7433. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  7434. with taicpu(hp4).oper[OperIdx]^ do
  7435. case typ of
  7436. top_reg:
  7437. if getsupreg(reg) = RS_EDX then
  7438. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7439. top_ref:
  7440. begin
  7441. if getsupreg(reg) = RS_EDX then
  7442. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7443. if getsupreg(reg) = RS_EDX then
  7444. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  7445. end;
  7446. else
  7447. ;
  7448. end;
  7449. end;
  7450. end;
  7451. {$else x86_64}
  7452. end;
  7453. end
  7454. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  7455. { the use of %rdx also covers the opsize being S_Q }
  7456. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  7457. begin
  7458. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  7459. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  7460. (taicpu(p).oper[1]^.reg = NR_RDX) then
  7461. begin
  7462. { Change:
  7463. movq %rax,%rdx
  7464. sarq $63,%rdx
  7465. To:
  7466. cqto
  7467. }
  7468. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  7469. RemoveInstruction(hp1);
  7470. taicpu(p).opcode := A_CQO;
  7471. taicpu(p).opsize := S_NO;
  7472. taicpu(p).clearop(1);
  7473. taicpu(p).clearop(0);
  7474. taicpu(p).ops:=0;
  7475. Result := True;
  7476. end
  7477. else if (cs_opt_size in current_settings.optimizerswitches) and
  7478. (taicpu(p).oper[0]^.reg = NR_RDX) and
  7479. (taicpu(p).oper[1]^.reg = NR_RAX) then
  7480. begin
  7481. { Change:
  7482. movq %rdx,%rax
  7483. sarq $63,%rdx
  7484. To:
  7485. movq %rdx,%rax
  7486. cqto
  7487. Note that this creates a dependency between the two instructions,
  7488. so only perform if optimising for size.
  7489. }
  7490. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  7491. taicpu(hp1).opcode := A_CQO;
  7492. taicpu(hp1).opsize := S_NO;
  7493. taicpu(hp1).clearop(1);
  7494. taicpu(hp1).clearop(0);
  7495. taicpu(hp1).ops:=0;
  7496. {$endif x86_64}
  7497. end;
  7498. end;
  7499. end
  7500. else if MatchInstruction(hp1, A_MOV, []) and
  7501. (taicpu(hp1).oper[1]^.typ = top_reg) then
  7502. { Though "GetNextInstruction" could be factored out, along with
  7503. the instructions that depend on hp2, it is an expensive call that
  7504. should be delayed for as long as possible, hence we do cheaper
  7505. checks first that are likely to be False. [Kit] }
  7506. begin
  7507. if (
  7508. (
  7509. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  7510. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  7511. (
  7512. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7513. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  7514. )
  7515. ) or
  7516. (
  7517. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  7518. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  7519. (
  7520. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7521. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  7522. )
  7523. )
  7524. ) and
  7525. GetNextInstruction(hp1, hp2) and
  7526. MatchInstruction(hp2, A_SAR, []) and
  7527. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  7528. begin
  7529. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  7530. begin
  7531. { Change:
  7532. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  7533. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  7534. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  7535. To:
  7536. movl r/m,%eax <- Note the change in register
  7537. cltd
  7538. }
  7539. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  7540. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  7541. taicpu(p).loadreg(1, NR_EAX);
  7542. taicpu(hp1).opcode := A_CDQ;
  7543. taicpu(hp1).clearop(1);
  7544. taicpu(hp1).clearop(0);
  7545. taicpu(hp1).ops:=0;
  7546. RemoveInstruction(hp2);
  7547. (*
  7548. {$ifdef x86_64}
  7549. end
  7550. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  7551. { This code sequence does not get generated - however it might become useful
  7552. if and when 128-bit signed integer types make an appearance, so the code
  7553. is kept here for when it is eventually needed. [Kit] }
  7554. (
  7555. (
  7556. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  7557. (
  7558. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7559. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  7560. )
  7561. ) or
  7562. (
  7563. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  7564. (
  7565. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  7566. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  7567. )
  7568. )
  7569. ) and
  7570. GetNextInstruction(hp1, hp2) and
  7571. MatchInstruction(hp2, A_SAR, [S_Q]) and
  7572. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  7573. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  7574. begin
  7575. { Change:
  7576. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  7577. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  7578. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  7579. To:
  7580. movq r/m,%rax <- Note the change in register
  7581. cqto
  7582. }
  7583. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  7584. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  7585. taicpu(p).loadreg(1, NR_RAX);
  7586. taicpu(hp1).opcode := A_CQO;
  7587. taicpu(hp1).clearop(1);
  7588. taicpu(hp1).clearop(0);
  7589. taicpu(hp1).ops:=0;
  7590. RemoveInstruction(hp2);
  7591. {$endif x86_64}
  7592. *)
  7593. end;
  7594. end;
  7595. {$ifdef x86_64}
  7596. end
  7597. else if (taicpu(p).opsize = S_L) and
  7598. (taicpu(p).oper[1]^.typ = top_reg) and
  7599. (
  7600. MatchInstruction(hp1, A_MOV,[]) and
  7601. (taicpu(hp1).opsize = S_L) and
  7602. (taicpu(hp1).oper[1]^.typ = top_reg)
  7603. ) and (
  7604. GetNextInstruction(hp1, hp2) and
  7605. (tai(hp2).typ=ait_instruction) and
  7606. (taicpu(hp2).opsize = S_Q) and
  7607. (
  7608. (
  7609. MatchInstruction(hp2, A_ADD,[]) and
  7610. (taicpu(hp2).opsize = S_Q) and
  7611. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7612. (
  7613. (
  7614. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7615. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7616. ) or (
  7617. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7618. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7619. )
  7620. )
  7621. ) or (
  7622. MatchInstruction(hp2, A_LEA,[]) and
  7623. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  7624. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  7625. (
  7626. (
  7627. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  7628. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7629. ) or (
  7630. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7631. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  7632. )
  7633. ) and (
  7634. (
  7635. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  7636. ) or (
  7637. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  7638. )
  7639. )
  7640. )
  7641. )
  7642. ) and (
  7643. GetNextInstruction(hp2, hp3) and
  7644. MatchInstruction(hp3, A_SHR,[]) and
  7645. (taicpu(hp3).opsize = S_Q) and
  7646. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  7647. (taicpu(hp3).oper[0]^.val = 1) and
  7648. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  7649. ) then
  7650. begin
  7651. { Change movl x, reg1d movl x, reg1d
  7652. movl y, reg2d movl y, reg2d
  7653. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  7654. shrq $1, reg1q shrq $1, reg1q
  7655. ( reg1d and reg2d can be switched around in the first two instructions )
  7656. To movl x, reg1d
  7657. addl y, reg1d
  7658. rcrl $1, reg1d
  7659. This corresponds to the common expression (x + y) shr 1, where
  7660. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  7661. smaller code, but won't account for x + y causing an overflow). [Kit]
  7662. }
  7663. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  7664. { Change first MOV command to have the same register as the final output }
  7665. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  7666. else
  7667. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  7668. { Change second MOV command to an ADD command. This is easier than
  7669. converting the existing command because it means we don't have to
  7670. touch 'y', which might be a complicated reference, and also the
  7671. fact that the third command might either be ADD or LEA. [Kit] }
  7672. taicpu(hp1).opcode := A_ADD;
  7673. { Delete old ADD/LEA instruction }
  7674. RemoveInstruction(hp2);
  7675. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  7676. taicpu(hp3).opcode := A_RCR;
  7677. taicpu(hp3).changeopsize(S_L);
  7678. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  7679. {$endif x86_64}
  7680. end;
  7681. end;
  7682. {$push}
  7683. {$q-}{$r-}
  7684. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  7685. var
  7686. ThisReg: TRegister;
  7687. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  7688. TargetSubReg: TSubRegister;
  7689. hp1, hp2: tai;
  7690. RegInUse, RegChanged, p_removed: Boolean;
  7691. { Store list of found instructions so we don't have to call
  7692. GetNextInstructionUsingReg multiple times }
  7693. InstrList: array of taicpu;
  7694. InstrMax, Index: Integer;
  7695. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  7696. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  7697. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  7698. WorkingValue: TCgInt;
  7699. PreMessage: string;
  7700. { Data flow analysis }
  7701. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  7702. BitwiseOnly, OrXorUsed,
  7703. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  7704. function CheckOverflowConditions: Boolean;
  7705. begin
  7706. Result := True;
  7707. if (TestValSignedMax > SignedUpperLimit) then
  7708. UpperSignedOverflow := True;
  7709. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  7710. LowerSignedOverflow := True;
  7711. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  7712. LowerUnsignedOverflow := True;
  7713. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  7714. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  7715. begin
  7716. { Absolute overflow }
  7717. Result := False;
  7718. Exit;
  7719. end;
  7720. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  7721. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  7722. ShiftDownOverflow := True;
  7723. if (TestValMin < 0) or (TestValMax < 0) then
  7724. begin
  7725. LowerUnsignedOverflow := True;
  7726. UpperUnsignedOverflow := True;
  7727. end;
  7728. end;
  7729. function AdjustInitialLoad: Boolean;
  7730. begin
  7731. Result := False;
  7732. if not p_removed then
  7733. begin
  7734. if TargetSize = MinSize then
  7735. begin
  7736. { Convert the input MOVZX to a MOV }
  7737. if (taicpu(p).oper[0]^.typ = top_reg) and
  7738. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  7739. begin
  7740. { Or remove it completely! }
  7741. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  7742. RemoveCurrentP(p);
  7743. p_removed := True;
  7744. end
  7745. else
  7746. begin
  7747. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  7748. taicpu(p).opcode := A_MOV;
  7749. taicpu(p).oper[1]^.reg := ThisReg;
  7750. taicpu(p).opsize := TargetSize;
  7751. end;
  7752. Result := True;
  7753. end
  7754. else if TargetSize <> MaxSize then
  7755. begin
  7756. case MaxSize of
  7757. S_L:
  7758. if TargetSize = S_W then
  7759. begin
  7760. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  7761. taicpu(p).opsize := S_BW;
  7762. taicpu(p).oper[1]^.reg := ThisReg;
  7763. Result := True;
  7764. end
  7765. else
  7766. InternalError(2020112341);
  7767. S_W:
  7768. if TargetSize = S_L then
  7769. begin
  7770. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  7771. taicpu(p).opsize := S_BL;
  7772. taicpu(p).oper[1]^.reg := ThisReg;
  7773. Result := True;
  7774. end
  7775. else
  7776. InternalError(2020112342);
  7777. else
  7778. ;
  7779. end;
  7780. end;
  7781. end;
  7782. end;
  7783. procedure AdjustFinalLoad;
  7784. begin
  7785. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  7786. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  7787. begin
  7788. { Convert the output MOVZX to a MOV }
  7789. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7790. begin
  7791. { Or remove it completely! }
  7792. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  7793. { Be careful; if p = hp1 and p was also removed, p
  7794. will become a dangling pointer }
  7795. if p = hp1 then
  7796. begin
  7797. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7798. p_removed := True;
  7799. end
  7800. else
  7801. RemoveInstruction(hp1);
  7802. end
  7803. else
  7804. begin
  7805. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  7806. taicpu(hp1).opcode := A_MOV;
  7807. taicpu(hp1).oper[0]^.reg := ThisReg;
  7808. taicpu(hp1).opsize := TargetSize;
  7809. end;
  7810. end
  7811. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  7812. begin
  7813. { Need to change the size of the output }
  7814. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  7815. taicpu(hp1).oper[0]^.reg := ThisReg;
  7816. taicpu(hp1).opsize := S_BL;
  7817. end;
  7818. end;
  7819. function CompressInstructions: Boolean;
  7820. var
  7821. LocalIndex: Integer;
  7822. begin
  7823. Result := False;
  7824. { The objective here is to try to find a combination that
  7825. removes one of the MOV/Z instructions. }
  7826. if (
  7827. (taicpu(p).oper[0]^.typ <> top_reg) or
  7828. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  7829. ) and
  7830. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7831. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7832. begin
  7833. { Make a preference to remove the second MOVZX instruction }
  7834. case taicpu(hp1).opsize of
  7835. S_BL, S_WL:
  7836. begin
  7837. TargetSize := S_L;
  7838. TargetSubReg := R_SUBD;
  7839. end;
  7840. S_BW:
  7841. begin
  7842. TargetSize := S_W;
  7843. TargetSubReg := R_SUBW;
  7844. end;
  7845. else
  7846. InternalError(2020112302);
  7847. end;
  7848. end
  7849. else
  7850. begin
  7851. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  7852. begin
  7853. { Exceeded lower bound but not upper bound }
  7854. TargetSize := MaxSize;
  7855. end
  7856. else if not LowerUnsignedOverflow then
  7857. begin
  7858. { Size didn't exceed lower bound }
  7859. TargetSize := MinSize;
  7860. end
  7861. else
  7862. Exit;
  7863. end;
  7864. case TargetSize of
  7865. S_B:
  7866. TargetSubReg := R_SUBL;
  7867. S_W:
  7868. TargetSubReg := R_SUBW;
  7869. S_L:
  7870. TargetSubReg := R_SUBD;
  7871. else
  7872. InternalError(2020112350);
  7873. end;
  7874. { Update the register to its new size }
  7875. setsubreg(ThisReg, TargetSubReg);
  7876. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  7877. begin
  7878. { Check to see if the active register is used afterwards;
  7879. if not, we can change it and make a saving. }
  7880. RegInUse := False;
  7881. TransferUsedRegs(TmpUsedRegs);
  7882. { The target register may be marked as in use to cross
  7883. a jump to a distant label, so exclude it }
  7884. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  7885. hp2 := p;
  7886. repeat
  7887. { Explicitly check for the excluded register (don't include the first
  7888. instruction as it may be reading from here }
  7889. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  7890. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  7891. begin
  7892. RegInUse := True;
  7893. Break;
  7894. end;
  7895. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  7896. if not GetNextInstruction(hp2, hp2) then
  7897. InternalError(2020112340);
  7898. until (hp2 = hp1);
  7899. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  7900. { We might still be able to get away with this }
  7901. RegInUse := not
  7902. (
  7903. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  7904. (hp2.typ = ait_instruction) and
  7905. (
  7906. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  7907. instruction that doesn't actually contain ThisReg }
  7908. (cs_opt_level3 in current_settings.optimizerswitches) or
  7909. RegInInstruction(ThisReg, hp2)
  7910. ) and
  7911. RegLoadedWithNewValue(ThisReg, hp2)
  7912. );
  7913. if not RegInUse then
  7914. begin
  7915. { Force the register size to the same as this instruction so it can be removed}
  7916. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  7917. begin
  7918. TargetSize := S_L;
  7919. TargetSubReg := R_SUBD;
  7920. end
  7921. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  7922. begin
  7923. TargetSize := S_W;
  7924. TargetSubReg := R_SUBW;
  7925. end;
  7926. ThisReg := taicpu(hp1).oper[1]^.reg;
  7927. setsubreg(ThisReg, TargetSubReg);
  7928. RegChanged := True;
  7929. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  7930. TransferUsedRegs(TmpUsedRegs);
  7931. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  7932. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  7933. if p = hp1 then
  7934. begin
  7935. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  7936. p_removed := True;
  7937. end
  7938. else
  7939. RemoveInstruction(hp1);
  7940. { Instruction will become "mov %reg,%reg" }
  7941. if not p_removed and (taicpu(p).opcode = A_MOV) and
  7942. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  7943. begin
  7944. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  7945. RemoveCurrentP(p);
  7946. p_removed := True;
  7947. end
  7948. else
  7949. taicpu(p).oper[1]^.reg := ThisReg;
  7950. Result := True;
  7951. end
  7952. else
  7953. begin
  7954. if TargetSize <> MaxSize then
  7955. begin
  7956. { Since the register is in use, we have to force it to
  7957. MaxSize otherwise part of it may become undefined later on }
  7958. TargetSize := MaxSize;
  7959. case TargetSize of
  7960. S_B:
  7961. TargetSubReg := R_SUBL;
  7962. S_W:
  7963. TargetSubReg := R_SUBW;
  7964. S_L:
  7965. TargetSubReg := R_SUBD;
  7966. else
  7967. InternalError(2020112351);
  7968. end;
  7969. setsubreg(ThisReg, TargetSubReg);
  7970. end;
  7971. AdjustFinalLoad;
  7972. end;
  7973. end
  7974. else
  7975. AdjustFinalLoad;
  7976. Result := AdjustInitialLoad or Result;
  7977. { Now go through every instruction we found and change the
  7978. size. If TargetSize = MaxSize, then almost no changes are
  7979. needed and Result can remain False if it hasn't been set
  7980. yet.
  7981. If RegChanged is True, then the register requires changing
  7982. and so the point about TargetSize = MaxSize doesn't apply. }
  7983. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  7984. begin
  7985. for LocalIndex := 0 to InstrMax do
  7986. begin
  7987. { If p_removed is true, then the original MOV/Z was removed
  7988. and removing the AND instruction may not be safe if it
  7989. appears first }
  7990. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  7991. InternalError(2020112310);
  7992. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  7993. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  7994. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  7995. InstrList[LocalIndex].opsize := TargetSize;
  7996. end;
  7997. Result := True;
  7998. end;
  7999. end;
  8000. begin
  8001. Result := False;
  8002. p_removed := False;
  8003. ThisReg := taicpu(p).oper[1]^.reg;
  8004. { Check for:
  8005. movs/z ###,%ecx (or %cx or %rcx)
  8006. ...
  8007. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8008. (dealloc %ecx)
  8009. Change to:
  8010. mov ###,%cl (if ### = %cl, then remove completely)
  8011. ...
  8012. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8013. }
  8014. if (getsupreg(ThisReg) = RS_ECX) and
  8015. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8016. (hp1.typ = ait_instruction) and
  8017. (
  8018. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8019. instruction that doesn't actually contain ECX }
  8020. (cs_opt_level3 in current_settings.optimizerswitches) or
  8021. RegInInstruction(NR_ECX, hp1) or
  8022. (
  8023. { It's common for the shift/rotate's read/write register to be
  8024. initialised in between, so under -O2 and under, search ahead
  8025. one more instruction
  8026. }
  8027. GetNextInstruction(hp1, hp1) and
  8028. (hp1.typ = ait_instruction) and
  8029. RegInInstruction(NR_ECX, hp1)
  8030. )
  8031. ) and
  8032. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8033. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8034. begin
  8035. TransferUsedRegs(TmpUsedRegs);
  8036. hp2 := p;
  8037. repeat
  8038. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8039. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8040. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8041. begin
  8042. case taicpu(p).opsize of
  8043. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8044. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  8045. begin
  8046. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  8047. RemoveCurrentP(p);
  8048. end
  8049. else
  8050. begin
  8051. taicpu(p).opcode := A_MOV;
  8052. taicpu(p).opsize := S_B;
  8053. taicpu(p).oper[1]^.reg := NR_CL;
  8054. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  8055. end;
  8056. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8057. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  8058. begin
  8059. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  8060. RemoveCurrentP(p);
  8061. end
  8062. else
  8063. begin
  8064. taicpu(p).opcode := A_MOV;
  8065. taicpu(p).opsize := S_W;
  8066. taicpu(p).oper[1]^.reg := NR_CX;
  8067. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  8068. end;
  8069. {$ifdef x86_64}
  8070. S_LQ:
  8071. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  8072. begin
  8073. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  8074. RemoveCurrentP(p);
  8075. end
  8076. else
  8077. begin
  8078. taicpu(p).opcode := A_MOV;
  8079. taicpu(p).opsize := S_L;
  8080. taicpu(p).oper[1]^.reg := NR_ECX;
  8081. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  8082. end;
  8083. {$endif x86_64}
  8084. else
  8085. InternalError(2021120401);
  8086. end;
  8087. Result := True;
  8088. Exit;
  8089. end;
  8090. end;
  8091. { This is anything but quick! }
  8092. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  8093. Exit;
  8094. SetLength(InstrList, 0);
  8095. InstrMax := -1;
  8096. case taicpu(p).opsize of
  8097. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8098. begin
  8099. {$if defined(i386) or defined(i8086)}
  8100. { If the target size is 8-bit, make sure we can actually encode it }
  8101. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  8102. Exit;
  8103. {$endif i386 or i8086}
  8104. LowerLimit := $FF;
  8105. SignedLowerLimit := $7F;
  8106. SignedLowerLimitBottom := -128;
  8107. MinSize := S_B;
  8108. if taicpu(p).opsize = S_BW then
  8109. begin
  8110. MaxSize := S_W;
  8111. UpperLimit := $FFFF;
  8112. SignedUpperLimit := $7FFF;
  8113. SignedUpperLimitBottom := -32768;
  8114. end
  8115. else
  8116. begin
  8117. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  8118. MaxSize := S_L;
  8119. UpperLimit := $FFFFFFFF;
  8120. SignedUpperLimit := $7FFFFFFF;
  8121. SignedUpperLimitBottom := -2147483648;
  8122. end;
  8123. end;
  8124. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8125. begin
  8126. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  8127. LowerLimit := $FFFF;
  8128. SignedLowerLimit := $7FFF;
  8129. SignedLowerLimitBottom := -32768;
  8130. UpperLimit := $FFFFFFFF;
  8131. SignedUpperLimit := $7FFFFFFF;
  8132. SignedUpperLimitBottom := -2147483648;
  8133. MinSize := S_W;
  8134. MaxSize := S_L;
  8135. end;
  8136. {$ifdef x86_64}
  8137. S_LQ:
  8138. begin
  8139. { Both the lower and upper limits are set to 32-bit. If a limit
  8140. is breached, then optimisation is impossible }
  8141. LowerLimit := $FFFFFFFF;
  8142. SignedLowerLimit := $7FFFFFFF;
  8143. SignedLowerLimitBottom := -2147483648;
  8144. UpperLimit := $FFFFFFFF;
  8145. SignedUpperLimit := $7FFFFFFF;
  8146. SignedUpperLimitBottom := -2147483648;
  8147. MinSize := S_L;
  8148. MaxSize := S_L;
  8149. end;
  8150. {$endif x86_64}
  8151. else
  8152. InternalError(2020112301);
  8153. end;
  8154. TestValMin := 0;
  8155. TestValMax := LowerLimit;
  8156. TestValSignedMax := SignedLowerLimit;
  8157. TryShiftDownLimit := LowerLimit;
  8158. TryShiftDown := S_NO;
  8159. ShiftDownOverflow := False;
  8160. RegChanged := False;
  8161. BitwiseOnly := True;
  8162. OrXorUsed := False;
  8163. UpperSignedOverflow := False;
  8164. LowerSignedOverflow := False;
  8165. UpperUnsignedOverflow := False;
  8166. LowerUnsignedOverflow := False;
  8167. hp1 := p;
  8168. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  8169. (hp1.typ = ait_instruction) and
  8170. (
  8171. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8172. instruction that doesn't actually contain ThisReg }
  8173. (cs_opt_level3 in current_settings.optimizerswitches) or
  8174. { This allows this Movx optimisation to work through the SETcc instructions
  8175. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8176. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8177. skip over these SETcc instructions). }
  8178. (taicpu(hp1).opcode = A_SETcc) or
  8179. RegInInstruction(ThisReg, hp1)
  8180. ) do
  8181. begin
  8182. case taicpu(hp1).opcode of
  8183. A_INC,A_DEC:
  8184. begin
  8185. { Has to be an exact match on the register }
  8186. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  8187. Break;
  8188. if taicpu(hp1).opcode = A_INC then
  8189. begin
  8190. Inc(TestValMin);
  8191. Inc(TestValMax);
  8192. Inc(TestValSignedMax);
  8193. end
  8194. else
  8195. begin
  8196. Dec(TestValMin);
  8197. Dec(TestValMax);
  8198. Dec(TestValSignedMax);
  8199. end;
  8200. end;
  8201. A_TEST, A_CMP:
  8202. begin
  8203. if (
  8204. { Too high a risk of non-linear behaviour that breaks DFA
  8205. here, unless it's cmp $0,%reg, which is equivalent to
  8206. test %reg,%reg }
  8207. OrXorUsed and
  8208. (taicpu(hp1).opcode = A_CMP) and
  8209. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  8210. ) or
  8211. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8212. { Has to be an exact match on the register }
  8213. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8214. (
  8215. { Permit "test %reg,%reg" }
  8216. (taicpu(hp1).opcode = A_TEST) and
  8217. (taicpu(hp1).oper[0]^.typ = top_reg) and
  8218. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  8219. ) or
  8220. (taicpu(hp1).oper[0]^.typ <> top_const) or
  8221. { Make sure the comparison value is not smaller than the
  8222. smallest allowed signed value for the minimum size (e.g.
  8223. -128 for 8-bit) }
  8224. not (
  8225. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  8226. { Is it in the negative range? }
  8227. (
  8228. (taicpu(hp1).oper[0]^.val < 0) and
  8229. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  8230. )
  8231. ) then
  8232. Break;
  8233. { Check to see if the active register is used afterwards }
  8234. TransferUsedRegs(TmpUsedRegs);
  8235. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  8236. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8237. begin
  8238. { Make sure the comparison or any previous instructions
  8239. hasn't pushed the test values outside of the range of
  8240. MinSize }
  8241. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8242. begin
  8243. { Exceeded lower bound but not upper bound }
  8244. TargetSize := MaxSize;
  8245. end
  8246. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  8247. begin
  8248. { Size didn't exceed lower bound }
  8249. TargetSize := MinSize;
  8250. end
  8251. else
  8252. Break;
  8253. case TargetSize of
  8254. S_B:
  8255. TargetSubReg := R_SUBL;
  8256. S_W:
  8257. TargetSubReg := R_SUBW;
  8258. S_L:
  8259. TargetSubReg := R_SUBD;
  8260. else
  8261. InternalError(2021051002);
  8262. end;
  8263. if TargetSize <> MaxSize then
  8264. begin
  8265. { Update the register to its new size }
  8266. setsubreg(ThisReg, TargetSubReg);
  8267. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  8268. taicpu(hp1).oper[1]^.reg := ThisReg;
  8269. taicpu(hp1).opsize := TargetSize;
  8270. { Convert the input MOVZX to a MOV if necessary }
  8271. AdjustInitialLoad;
  8272. if (InstrMax >= 0) then
  8273. begin
  8274. for Index := 0 to InstrMax do
  8275. begin
  8276. { If p_removed is true, then the original MOV/Z was removed
  8277. and removing the AND instruction may not be safe if it
  8278. appears first }
  8279. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  8280. InternalError(2020112311);
  8281. if InstrList[Index].oper[0]^.typ = top_reg then
  8282. InstrList[Index].oper[0]^.reg := ThisReg;
  8283. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  8284. InstrList[Index].opsize := MinSize;
  8285. end;
  8286. end;
  8287. Result := True;
  8288. end;
  8289. Exit;
  8290. end;
  8291. end;
  8292. A_SETcc:
  8293. begin
  8294. { This allows this Movx optimisation to work through the SETcc instructions
  8295. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  8296. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  8297. skip over these SETcc instructions). }
  8298. if (cs_opt_level3 in current_settings.optimizerswitches) or
  8299. { Of course, break out if the current register is used }
  8300. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  8301. Break
  8302. else
  8303. { We must use Continue so the instruction doesn't get added
  8304. to InstrList }
  8305. Continue;
  8306. end;
  8307. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  8308. begin
  8309. if
  8310. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  8311. { Has to be an exact match on the register }
  8312. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  8313. (
  8314. (
  8315. (taicpu(hp1).oper[0]^.typ = top_const) and
  8316. (
  8317. (
  8318. (taicpu(hp1).opcode = A_SHL) and
  8319. (
  8320. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  8321. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  8322. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  8323. )
  8324. ) or (
  8325. (taicpu(hp1).opcode <> A_SHL) and
  8326. (
  8327. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8328. { Is it in the negative range? }
  8329. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  8330. )
  8331. )
  8332. )
  8333. ) or (
  8334. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  8335. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  8336. )
  8337. ) then
  8338. Break;
  8339. { Only process OR and XOR if there are only bitwise operations,
  8340. since otherwise they can too easily fool the data flow
  8341. analysis (they can cause non-linear behaviour) }
  8342. case taicpu(hp1).opcode of
  8343. A_ADD:
  8344. begin
  8345. if OrXorUsed then
  8346. { Too high a risk of non-linear behaviour that breaks DFA here }
  8347. Break
  8348. else
  8349. BitwiseOnly := False;
  8350. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8351. begin
  8352. TestValMin := TestValMin * 2;
  8353. TestValMax := TestValMax * 2;
  8354. TestValSignedMax := TestValSignedMax * 2;
  8355. end
  8356. else
  8357. begin
  8358. WorkingValue := taicpu(hp1).oper[0]^.val;
  8359. TestValMin := TestValMin + WorkingValue;
  8360. TestValMax := TestValMax + WorkingValue;
  8361. TestValSignedMax := TestValSignedMax + WorkingValue;
  8362. end;
  8363. end;
  8364. A_SUB:
  8365. begin
  8366. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8367. begin
  8368. TestValMin := 0;
  8369. TestValMax := 0;
  8370. TestValSignedMax := 0;
  8371. end
  8372. else
  8373. begin
  8374. if OrXorUsed then
  8375. { Too high a risk of non-linear behaviour that breaks DFA here }
  8376. Break
  8377. else
  8378. BitwiseOnly := False;
  8379. WorkingValue := taicpu(hp1).oper[0]^.val;
  8380. TestValMin := TestValMin - WorkingValue;
  8381. TestValMax := TestValMax - WorkingValue;
  8382. TestValSignedMax := TestValSignedMax - WorkingValue;
  8383. end;
  8384. end;
  8385. A_AND:
  8386. if (taicpu(hp1).oper[0]^.typ = top_const) then
  8387. begin
  8388. { we might be able to go smaller if AND appears first }
  8389. if InstrMax = -1 then
  8390. case MinSize of
  8391. S_B:
  8392. ;
  8393. S_W:
  8394. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8395. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8396. begin
  8397. TryShiftDown := S_B;
  8398. TryShiftDownLimit := $FF;
  8399. end;
  8400. S_L:
  8401. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  8402. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  8403. begin
  8404. TryShiftDown := S_B;
  8405. TryShiftDownLimit := $FF;
  8406. end
  8407. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  8408. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  8409. begin
  8410. TryShiftDown := S_W;
  8411. TryShiftDownLimit := $FFFF;
  8412. end;
  8413. else
  8414. InternalError(2020112320);
  8415. end;
  8416. WorkingValue := taicpu(hp1).oper[0]^.val;
  8417. TestValMin := TestValMin and WorkingValue;
  8418. TestValMax := TestValMax and WorkingValue;
  8419. TestValSignedMax := TestValSignedMax and WorkingValue;
  8420. end;
  8421. A_OR:
  8422. begin
  8423. if not BitwiseOnly then
  8424. Break;
  8425. OrXorUsed := True;
  8426. WorkingValue := taicpu(hp1).oper[0]^.val;
  8427. TestValMin := TestValMin or WorkingValue;
  8428. TestValMax := TestValMax or WorkingValue;
  8429. TestValSignedMax := TestValSignedMax or WorkingValue;
  8430. end;
  8431. A_XOR:
  8432. begin
  8433. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  8434. begin
  8435. TestValMin := 0;
  8436. TestValMax := 0;
  8437. TestValSignedMax := 0;
  8438. end
  8439. else
  8440. begin
  8441. if not BitwiseOnly then
  8442. Break;
  8443. OrXorUsed := True;
  8444. WorkingValue := taicpu(hp1).oper[0]^.val;
  8445. TestValMin := TestValMin xor WorkingValue;
  8446. TestValMax := TestValMax xor WorkingValue;
  8447. TestValSignedMax := TestValSignedMax xor WorkingValue;
  8448. end;
  8449. end;
  8450. A_SHL:
  8451. begin
  8452. BitwiseOnly := False;
  8453. WorkingValue := taicpu(hp1).oper[0]^.val;
  8454. TestValMin := TestValMin shl WorkingValue;
  8455. TestValMax := TestValMax shl WorkingValue;
  8456. TestValSignedMax := TestValSignedMax shl WorkingValue;
  8457. end;
  8458. A_SHR,
  8459. { The first instruction was MOVZX, so the value won't be negative }
  8460. A_SAR:
  8461. begin
  8462. if InstrMax <> -1 then
  8463. BitwiseOnly := False
  8464. else
  8465. { we might be able to go smaller if SHR appears first }
  8466. case MinSize of
  8467. S_B:
  8468. ;
  8469. S_W:
  8470. if (taicpu(hp1).oper[0]^.val >= 8) then
  8471. begin
  8472. TryShiftDown := S_B;
  8473. TryShiftDownLimit := $FF;
  8474. TryShiftDownSignedLimit := $7F;
  8475. TryShiftDownSignedLimitLower := -128;
  8476. end;
  8477. S_L:
  8478. if (taicpu(hp1).oper[0]^.val >= 24) then
  8479. begin
  8480. TryShiftDown := S_B;
  8481. TryShiftDownLimit := $FF;
  8482. TryShiftDownSignedLimit := $7F;
  8483. TryShiftDownSignedLimitLower := -128;
  8484. end
  8485. else if (taicpu(hp1).oper[0]^.val >= 16) then
  8486. begin
  8487. TryShiftDown := S_W;
  8488. TryShiftDownLimit := $FFFF;
  8489. TryShiftDownSignedLimit := $7FFF;
  8490. TryShiftDownSignedLimitLower := -32768;
  8491. end;
  8492. else
  8493. InternalError(2020112321);
  8494. end;
  8495. WorkingValue := taicpu(hp1).oper[0]^.val;
  8496. if taicpu(hp1).opcode = A_SAR then
  8497. begin
  8498. TestValMin := SarInt64(TestValMin, WorkingValue);
  8499. TestValMax := SarInt64(TestValMax, WorkingValue);
  8500. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  8501. end
  8502. else
  8503. begin
  8504. TestValMin := TestValMin shr WorkingValue;
  8505. TestValMax := TestValMax shr WorkingValue;
  8506. TestValSignedMax := TestValSignedMax shr WorkingValue;
  8507. end;
  8508. end;
  8509. else
  8510. InternalError(2020112303);
  8511. end;
  8512. end;
  8513. (*
  8514. A_IMUL:
  8515. case taicpu(hp1).ops of
  8516. 2:
  8517. begin
  8518. if not MatchOpType(hp1, top_reg, top_reg) or
  8519. { Has to be an exact match on the register }
  8520. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  8521. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  8522. Break;
  8523. TestValMin := TestValMin * TestValMin;
  8524. TestValMax := TestValMax * TestValMax;
  8525. TestValSignedMax := TestValSignedMax * TestValMax;
  8526. end;
  8527. 3:
  8528. begin
  8529. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8530. { Has to be an exact match on the register }
  8531. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8532. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8533. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8534. { Is it in the negative range? }
  8535. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8536. Break;
  8537. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  8538. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  8539. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  8540. end;
  8541. else
  8542. Break;
  8543. end;
  8544. A_IDIV:
  8545. case taicpu(hp1).ops of
  8546. 3:
  8547. begin
  8548. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  8549. { Has to be an exact match on the register }
  8550. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  8551. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  8552. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  8553. { Is it in the negative range? }
  8554. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  8555. Break;
  8556. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  8557. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  8558. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  8559. end;
  8560. else
  8561. Break;
  8562. end;
  8563. *)
  8564. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8565. begin
  8566. { If there are no instructions in between, then we might be able to make a saving }
  8567. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  8568. Break;
  8569. { We have something like:
  8570. movzbw %dl,%dx
  8571. ...
  8572. movswl %dx,%edx
  8573. Change the latter to a zero-extension then enter the
  8574. A_MOVZX case branch.
  8575. }
  8576. {$ifdef x86_64}
  8577. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8578. begin
  8579. { this becomes a zero extension from 32-bit to 64-bit, but
  8580. the upper 32 bits are already zero, so just delete the
  8581. instruction }
  8582. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  8583. RemoveInstruction(hp1);
  8584. Result := True;
  8585. Exit;
  8586. end
  8587. else
  8588. {$endif x86_64}
  8589. begin
  8590. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  8591. taicpu(hp1).opcode := A_MOVZX;
  8592. {$ifdef x86_64}
  8593. case taicpu(hp1).opsize of
  8594. S_BQ:
  8595. begin
  8596. taicpu(hp1).opsize := S_BL;
  8597. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8598. end;
  8599. S_WQ:
  8600. begin
  8601. taicpu(hp1).opsize := S_WL;
  8602. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8603. end;
  8604. S_LQ:
  8605. begin
  8606. taicpu(hp1).opcode := A_MOV;
  8607. taicpu(hp1).opsize := S_L;
  8608. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  8609. { In this instance, we need to break out because the
  8610. instruction is no longer MOVZX or MOVSXD }
  8611. Result := True;
  8612. Exit;
  8613. end;
  8614. else
  8615. ;
  8616. end;
  8617. {$endif x86_64}
  8618. Result := CompressInstructions;
  8619. Exit;
  8620. end;
  8621. end;
  8622. A_MOVZX:
  8623. begin
  8624. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  8625. Break;
  8626. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  8627. begin
  8628. if (InstrMax = -1) and
  8629. { Will return false if the second parameter isn't ThisReg
  8630. (can happen on -O2 and under) }
  8631. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8632. begin
  8633. { The two MOVZX instructions are adjacent, so remove the first one }
  8634. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  8635. RemoveCurrentP(p);
  8636. Result := True;
  8637. Exit;
  8638. end;
  8639. Break;
  8640. end;
  8641. Result := CompressInstructions;
  8642. Exit;
  8643. end;
  8644. else
  8645. { This includes ADC, SBB and IDIV }
  8646. Break;
  8647. end;
  8648. if not CheckOverflowConditions then
  8649. Break;
  8650. { Contains highest index (so instruction count - 1) }
  8651. Inc(InstrMax);
  8652. if InstrMax > High(InstrList) then
  8653. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8654. InstrList[InstrMax] := taicpu(hp1);
  8655. end;
  8656. end;
  8657. {$pop}
  8658. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  8659. var
  8660. hp1 : tai;
  8661. begin
  8662. Result:=false;
  8663. if (taicpu(p).ops >= 2) and
  8664. ((taicpu(p).oper[0]^.typ = top_const) or
  8665. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  8666. (taicpu(p).oper[1]^.typ = top_reg) and
  8667. ((taicpu(p).ops = 2) or
  8668. ((taicpu(p).oper[2]^.typ = top_reg) and
  8669. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  8670. GetLastInstruction(p,hp1) and
  8671. MatchInstruction(hp1,A_MOV,[]) and
  8672. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8673. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8674. begin
  8675. TransferUsedRegs(TmpUsedRegs);
  8676. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  8677. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  8678. { change
  8679. mov reg1,reg2
  8680. imul y,reg2 to imul y,reg1,reg2 }
  8681. begin
  8682. taicpu(p).ops := 3;
  8683. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  8684. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  8685. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  8686. RemoveInstruction(hp1);
  8687. result:=true;
  8688. end;
  8689. end;
  8690. end;
  8691. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  8692. var
  8693. ThisLabel: TAsmLabel;
  8694. begin
  8695. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  8696. ThisLabel.decrefs;
  8697. taicpu(p).opcode := A_RET;
  8698. taicpu(p).is_jmp := false;
  8699. taicpu(p).ops := taicpu(ret_p).ops;
  8700. case taicpu(ret_p).ops of
  8701. 0:
  8702. taicpu(p).clearop(0);
  8703. 1:
  8704. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  8705. else
  8706. internalerror(2016041301);
  8707. end;
  8708. { If the original label is now dead, it might turn out that the label
  8709. immediately follows p. As a result, everything beyond it, which will
  8710. be just some final register configuration and a RET instruction, is
  8711. now dead code. [Kit] }
  8712. { NOTE: This is much faster than introducing a OptPass2RET routine and
  8713. running RemoveDeadCodeAfterJump for each RET instruction, because
  8714. this optimisation rarely happens and most RETs appear at the end of
  8715. routines where there is nothing that can be stripped. [Kit] }
  8716. if not ThisLabel.is_used then
  8717. RemoveDeadCodeAfterJump(p);
  8718. end;
  8719. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  8720. var
  8721. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  8722. Unconditional, PotentialModified: Boolean;
  8723. OperPtr: POper;
  8724. NewRef: TReference;
  8725. InstrList: array of taicpu;
  8726. InstrMax, Index: Integer;
  8727. const
  8728. {$ifdef DEBUG_AOPTCPU}
  8729. SNoFlags: shortstring = ' so the flags aren''t modified';
  8730. {$else DEBUG_AOPTCPU}
  8731. SNoFlags = '';
  8732. {$endif DEBUG_AOPTCPU}
  8733. begin
  8734. Result:=false;
  8735. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  8736. begin
  8737. if MatchInstruction(hp1, A_TEST, [S_B]) and
  8738. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8739. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8740. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  8741. GetNextInstruction(hp1, hp2) and
  8742. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  8743. { Change from: To:
  8744. set(C) %reg j(~C) label
  8745. test %reg,%reg/cmp $0,%reg
  8746. je label
  8747. set(C) %reg j(C) label
  8748. test %reg,%reg/cmp $0,%reg
  8749. jne label
  8750. (Also do something similar with sete/setne instead of je/jne)
  8751. }
  8752. begin
  8753. { Before we do anything else, we need to check the instructions
  8754. in between SETcc and TEST to make sure they don't modify the
  8755. FLAGS register - if -O2 or under, there won't be any
  8756. instructions between SET and TEST }
  8757. TransferUsedRegs(TmpUsedRegs);
  8758. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8759. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8760. begin
  8761. next := p;
  8762. SetLength(InstrList, 0);
  8763. InstrMax := -1;
  8764. PotentialModified := False;
  8765. { Make a note of every instruction that modifies the FLAGS
  8766. register }
  8767. while GetNextInstruction(next, next) and (next <> hp1) do
  8768. begin
  8769. if next.typ <> ait_instruction then
  8770. { GetNextInstructionUsingReg should have returned False }
  8771. InternalError(2021051701);
  8772. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  8773. begin
  8774. case taicpu(next).opcode of
  8775. A_SETcc,
  8776. A_CMOVcc,
  8777. A_Jcc:
  8778. begin
  8779. if PotentialModified then
  8780. { Not safe because the flags were modified earlier }
  8781. Exit
  8782. else
  8783. { Condition is the same as the initial SETcc, so this is safe
  8784. (don't add to instruction list though) }
  8785. Continue;
  8786. end;
  8787. A_ADD:
  8788. begin
  8789. if (taicpu(next).opsize = S_B) or
  8790. { LEA doesn't support 8-bit operands }
  8791. (taicpu(next).oper[1]^.typ <> top_reg) or
  8792. { Must write to a register }
  8793. (taicpu(next).oper[0]^.typ = top_ref) then
  8794. { Require a constant or a register }
  8795. Exit;
  8796. PotentialModified := True;
  8797. end;
  8798. A_SUB:
  8799. begin
  8800. if (taicpu(next).opsize = S_B) or
  8801. { LEA doesn't support 8-bit operands }
  8802. (taicpu(next).oper[1]^.typ <> top_reg) or
  8803. { Must write to a register }
  8804. (taicpu(next).oper[0]^.typ <> top_const) or
  8805. (taicpu(next).oper[0]^.val = $80000000) then
  8806. { Can't subtract a register with LEA - also
  8807. check that the value isn't -2^31, as this
  8808. can't be negated }
  8809. Exit;
  8810. PotentialModified := True;
  8811. end;
  8812. A_SAL,
  8813. A_SHL:
  8814. begin
  8815. if (taicpu(next).opsize = S_B) or
  8816. { LEA doesn't support 8-bit operands }
  8817. (taicpu(next).oper[1]^.typ <> top_reg) or
  8818. { Must write to a register }
  8819. (taicpu(next).oper[0]^.typ <> top_const) or
  8820. (taicpu(next).oper[0]^.val < 0) or
  8821. (taicpu(next).oper[0]^.val > 3) then
  8822. Exit;
  8823. PotentialModified := True;
  8824. end;
  8825. A_IMUL:
  8826. begin
  8827. if (taicpu(next).ops <> 3) or
  8828. (taicpu(next).oper[1]^.typ <> top_reg) or
  8829. { Must write to a register }
  8830. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  8831. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  8832. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  8833. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  8834. Exit
  8835. else
  8836. PotentialModified := True;
  8837. end;
  8838. else
  8839. { Don't know how to change this, so abort }
  8840. Exit;
  8841. end;
  8842. { Contains highest index (so instruction count - 1) }
  8843. Inc(InstrMax);
  8844. if InstrMax > High(InstrList) then
  8845. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  8846. InstrList[InstrMax] := taicpu(next);
  8847. end;
  8848. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  8849. end;
  8850. if not Assigned(next) or (next <> hp1) then
  8851. { It should be equal to hp1 }
  8852. InternalError(2021051702);
  8853. { Cycle through each instruction and check to see if we can
  8854. change them to versions that don't modify the flags }
  8855. if (InstrMax >= 0) then
  8856. begin
  8857. for Index := 0 to InstrMax do
  8858. case InstrList[Index].opcode of
  8859. A_ADD:
  8860. begin
  8861. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  8862. InstrList[Index].opcode := A_LEA;
  8863. reference_reset(NewRef, 1, []);
  8864. NewRef.base := InstrList[Index].oper[1]^.reg;
  8865. if InstrList[Index].oper[0]^.typ = top_reg then
  8866. begin
  8867. NewRef.index := InstrList[Index].oper[0]^.reg;
  8868. NewRef.scalefactor := 1;
  8869. end
  8870. else
  8871. NewRef.offset := InstrList[Index].oper[0]^.val;
  8872. InstrList[Index].loadref(0, NewRef);
  8873. end;
  8874. A_SUB:
  8875. begin
  8876. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  8877. InstrList[Index].opcode := A_LEA;
  8878. reference_reset(NewRef, 1, []);
  8879. NewRef.base := InstrList[Index].oper[1]^.reg;
  8880. NewRef.offset := -InstrList[Index].oper[0]^.val;
  8881. InstrList[Index].loadref(0, NewRef);
  8882. end;
  8883. A_SHL,
  8884. A_SAL:
  8885. begin
  8886. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  8887. InstrList[Index].opcode := A_LEA;
  8888. reference_reset(NewRef, 1, []);
  8889. NewRef.index := InstrList[Index].oper[1]^.reg;
  8890. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  8891. InstrList[Index].loadref(0, NewRef);
  8892. end;
  8893. A_IMUL:
  8894. begin
  8895. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  8896. InstrList[Index].opcode := A_LEA;
  8897. reference_reset(NewRef, 1, []);
  8898. NewRef.index := InstrList[Index].oper[1]^.reg;
  8899. case InstrList[Index].oper[0]^.val of
  8900. 2, 4, 8:
  8901. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  8902. else {3, 5 and 9}
  8903. begin
  8904. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  8905. NewRef.base := InstrList[Index].oper[1]^.reg;
  8906. end;
  8907. end;
  8908. InstrList[Index].loadref(0, NewRef);
  8909. end;
  8910. else
  8911. InternalError(2021051710);
  8912. end;
  8913. end;
  8914. { Mark the FLAGS register as used across this whole block }
  8915. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  8916. end;
  8917. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  8918. JumpC := taicpu(hp2).condition;
  8919. Unconditional := False;
  8920. if conditions_equal(JumpC, C_E) then
  8921. SetC := inverse_cond(taicpu(p).condition)
  8922. else if conditions_equal(JumpC, C_NE) then
  8923. SetC := taicpu(p).condition
  8924. else
  8925. { We've got something weird here (and inefficent) }
  8926. begin
  8927. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  8928. SetC := C_NONE;
  8929. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  8930. if condition_in(C_AE, JumpC) then
  8931. Unconditional := True
  8932. else
  8933. { Not sure what to do with this jump - drop out }
  8934. Exit;
  8935. end;
  8936. RemoveInstruction(hp1);
  8937. if Unconditional then
  8938. MakeUnconditional(taicpu(hp2))
  8939. else
  8940. begin
  8941. if SetC = C_NONE then
  8942. InternalError(2018061402);
  8943. taicpu(hp2).SetCondition(SetC);
  8944. end;
  8945. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  8946. TmpUsedRegs }
  8947. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  8948. begin
  8949. RemoveCurrentp(p, hp2);
  8950. if taicpu(hp2).opcode = A_SETcc then
  8951. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  8952. else
  8953. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  8954. end
  8955. else
  8956. if taicpu(hp2).opcode = A_SETcc then
  8957. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  8958. else
  8959. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  8960. Result := True;
  8961. end
  8962. else if
  8963. { Make sure the instructions are adjacent }
  8964. (
  8965. not (cs_opt_level3 in current_settings.optimizerswitches) or
  8966. GetNextInstruction(p, hp1)
  8967. ) and
  8968. MatchInstruction(hp1, A_MOV, [S_B]) and
  8969. { Writing to memory is allowed }
  8970. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  8971. begin
  8972. {
  8973. Watch out for sequences such as:
  8974. set(c)b %regb
  8975. movb %regb,(ref)
  8976. movb $0,1(ref)
  8977. movb $0,2(ref)
  8978. movb $0,3(ref)
  8979. Much more efficient to turn it into:
  8980. movl $0,%regl
  8981. set(c)b %regb
  8982. movl %regl,(ref)
  8983. Or:
  8984. set(c)b %regb
  8985. movzbl %regb,%regl
  8986. movl %regl,(ref)
  8987. }
  8988. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  8989. GetNextInstruction(hp1, hp2) and
  8990. MatchInstruction(hp2, A_MOV, [S_B]) and
  8991. (taicpu(hp2).oper[1]^.typ = top_ref) and
  8992. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  8993. begin
  8994. { Don't do anything else except set Result to True }
  8995. end
  8996. else
  8997. begin
  8998. if taicpu(p).oper[0]^.typ = top_reg then
  8999. begin
  9000. TransferUsedRegs(TmpUsedRegs);
  9001. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9002. end;
  9003. { If it's not a register, it's a memory address }
  9004. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9005. begin
  9006. { Even if the register is still in use, we can minimise the
  9007. pipeline stall by changing the MOV into another SETcc. }
  9008. taicpu(hp1).opcode := A_SETcc;
  9009. taicpu(hp1).condition := taicpu(p).condition;
  9010. if taicpu(hp1).oper[1]^.typ = top_ref then
  9011. begin
  9012. { Swapping the operand pointers like this is probably a
  9013. bit naughty, but it is far faster than using loadoper
  9014. to transfer the reference from oper[1] to oper[0] if
  9015. you take into account the extra procedure calls and
  9016. the memory allocation and deallocation required }
  9017. OperPtr := taicpu(hp1).oper[1];
  9018. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9019. taicpu(hp1).oper[0] := OperPtr;
  9020. end
  9021. else
  9022. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9023. taicpu(hp1).clearop(1);
  9024. taicpu(hp1).ops := 1;
  9025. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9026. end
  9027. else
  9028. begin
  9029. if taicpu(hp1).oper[1]^.typ = top_reg then
  9030. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9031. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9032. RemoveInstruction(hp1);
  9033. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9034. end
  9035. end;
  9036. Result := True;
  9037. end;
  9038. end;
  9039. end;
  9040. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  9041. var
  9042. hp1: tai;
  9043. Count: Integer;
  9044. OrigLabel: TAsmLabel;
  9045. begin
  9046. result := False;
  9047. { Sometimes, the optimisations below can permit this }
  9048. RemoveDeadCodeAfterJump(p);
  9049. 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
  9050. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  9051. begin
  9052. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9053. { Also a side-effect of optimisations }
  9054. if CollapseZeroDistJump(p, OrigLabel) then
  9055. begin
  9056. Result := True;
  9057. Exit;
  9058. end;
  9059. hp1 := GetLabelWithSym(OrigLabel);
  9060. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  9061. begin
  9062. case taicpu(hp1).opcode of
  9063. A_RET:
  9064. {
  9065. change
  9066. jmp .L1
  9067. ...
  9068. .L1:
  9069. ret
  9070. into
  9071. ret
  9072. }
  9073. begin
  9074. ConvertJumpToRET(p, hp1);
  9075. result:=true;
  9076. end;
  9077. { Check any kind of direct assignment instruction }
  9078. A_MOV,
  9079. A_MOVD,
  9080. A_MOVQ,
  9081. A_MOVSX,
  9082. {$ifdef x86_64}
  9083. A_MOVSXD,
  9084. {$endif x86_64}
  9085. A_MOVZX,
  9086. A_MOVAPS,
  9087. A_MOVUPS,
  9088. A_MOVSD,
  9089. A_MOVAPD,
  9090. A_MOVUPD,
  9091. A_MOVDQA,
  9092. A_MOVDQU,
  9093. A_VMOVSS,
  9094. A_VMOVAPS,
  9095. A_VMOVUPS,
  9096. A_VMOVSD,
  9097. A_VMOVAPD,
  9098. A_VMOVUPD,
  9099. A_VMOVDQA,
  9100. A_VMOVDQU:
  9101. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  9102. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  9103. begin
  9104. Result := True;
  9105. Exit;
  9106. end;
  9107. else
  9108. ;
  9109. end;
  9110. end;
  9111. end;
  9112. end;
  9113. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  9114. begin
  9115. CanBeCMOV:=assigned(p) and
  9116. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  9117. { we can't use cmov ref,reg because
  9118. ref could be nil and cmov still throws an exception
  9119. if ref=nil but the mov isn't done (FK)
  9120. or ((taicpu(p).oper[0]^.typ = top_ref) and
  9121. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  9122. }
  9123. (taicpu(p).oper[1]^.typ = top_reg) and
  9124. (
  9125. (taicpu(p).oper[0]^.typ = top_reg) or
  9126. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  9127. it is not expected that this can cause a seg. violation }
  9128. (
  9129. (taicpu(p).oper[0]^.typ = top_ref) and
  9130. IsRefSafe(taicpu(p).oper[0]^.ref)
  9131. )
  9132. );
  9133. end;
  9134. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  9135. var
  9136. hp1,hp2: tai;
  9137. {$ifndef i8086}
  9138. hp3,hp4,hpmov2, hp5: tai;
  9139. l : Longint;
  9140. condition : TAsmCond;
  9141. {$endif i8086}
  9142. carryadd_opcode : TAsmOp;
  9143. symbol: TAsmSymbol;
  9144. increg, tmpreg: TRegister;
  9145. begin
  9146. result:=false;
  9147. if GetNextInstruction(p,hp1) then
  9148. begin
  9149. if (hp1.typ=ait_label) then
  9150. begin
  9151. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  9152. Exit;
  9153. end
  9154. else if (hp1.typ<>ait_instruction) then
  9155. Exit;
  9156. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9157. if (
  9158. (
  9159. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  9160. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  9161. (Taicpu(hp1).oper[0]^.val=1)
  9162. ) or
  9163. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  9164. ) and
  9165. GetNextInstruction(hp1,hp2) and
  9166. SkipAligns(hp2, hp2) and
  9167. (hp2.typ = ait_label) and
  9168. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  9169. { jb @@1 cmc
  9170. inc/dec operand --> adc/sbb operand,0
  9171. @@1:
  9172. ... and ...
  9173. jnb @@1
  9174. inc/dec operand --> adc/sbb operand,0
  9175. @@1: }
  9176. begin
  9177. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  9178. begin
  9179. case taicpu(hp1).opcode of
  9180. A_INC,
  9181. A_ADD:
  9182. carryadd_opcode:=A_ADC;
  9183. A_DEC,
  9184. A_SUB:
  9185. carryadd_opcode:=A_SBB;
  9186. else
  9187. InternalError(2021011001);
  9188. end;
  9189. Taicpu(p).clearop(0);
  9190. Taicpu(p).ops:=0;
  9191. Taicpu(p).is_jmp:=false;
  9192. Taicpu(p).opcode:=A_CMC;
  9193. Taicpu(p).condition:=C_NONE;
  9194. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  9195. Taicpu(hp1).ops:=2;
  9196. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9197. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9198. else
  9199. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9200. Taicpu(hp1).loadconst(0,0);
  9201. Taicpu(hp1).opcode:=carryadd_opcode;
  9202. result:=true;
  9203. exit;
  9204. end
  9205. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  9206. begin
  9207. case taicpu(hp1).opcode of
  9208. A_INC,
  9209. A_ADD:
  9210. carryadd_opcode:=A_ADC;
  9211. A_DEC,
  9212. A_SUB:
  9213. carryadd_opcode:=A_SBB;
  9214. else
  9215. InternalError(2021011002);
  9216. end;
  9217. Taicpu(hp1).ops:=2;
  9218. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  9219. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  9220. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  9221. else
  9222. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  9223. Taicpu(hp1).loadconst(0,0);
  9224. Taicpu(hp1).opcode:=carryadd_opcode;
  9225. RemoveCurrentP(p, hp1);
  9226. result:=true;
  9227. exit;
  9228. end
  9229. {
  9230. jcc @@1 setcc tmpreg
  9231. inc/dec/add/sub operand -> (movzx tmpreg)
  9232. @@1: add/sub tmpreg,operand
  9233. While this increases code size slightly, it makes the code much faster if the
  9234. jump is unpredictable
  9235. }
  9236. else if not(cs_opt_size in current_settings.optimizerswitches) then
  9237. begin
  9238. { search for an available register which is volatile }
  9239. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  9240. if increg <> NR_NO then
  9241. begin
  9242. { We don't need to check if tmpreg is in hp1 or not, because
  9243. it will be marked as in use at p (if not, this is
  9244. indictive of a compiler bug). }
  9245. TAsmLabel(symbol).decrefs;
  9246. Taicpu(p).clearop(0);
  9247. Taicpu(p).ops:=1;
  9248. Taicpu(p).is_jmp:=false;
  9249. Taicpu(p).opcode:=A_SETcc;
  9250. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  9251. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  9252. Taicpu(p).loadreg(0,increg);
  9253. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  9254. begin
  9255. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  9256. R_SUBW:
  9257. begin
  9258. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  9259. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  9260. end;
  9261. R_SUBD:
  9262. begin
  9263. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9264. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9265. end;
  9266. {$ifdef x86_64}
  9267. R_SUBQ:
  9268. begin
  9269. { MOVZX doesn't have a 64-bit variant, because
  9270. the 32-bit version implicitly zeroes the
  9271. upper 32-bits of the destination register }
  9272. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  9273. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  9274. setsubreg(tmpreg, R_SUBQ);
  9275. end;
  9276. {$endif x86_64}
  9277. else
  9278. Internalerror(2020030601);
  9279. end;
  9280. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  9281. asml.InsertAfter(hp2,p);
  9282. end
  9283. else
  9284. tmpreg := increg;
  9285. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  9286. begin
  9287. Taicpu(hp1).ops:=2;
  9288. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  9289. end;
  9290. Taicpu(hp1).loadreg(0,tmpreg);
  9291. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  9292. Result := True;
  9293. { p is no longer a Jcc instruction, so exit }
  9294. Exit;
  9295. end;
  9296. end;
  9297. end;
  9298. { Detect the following:
  9299. jmp<cond> @Lbl1
  9300. jmp @Lbl2
  9301. ...
  9302. @Lbl1:
  9303. ret
  9304. Change to:
  9305. jmp<inv_cond> @Lbl2
  9306. ret
  9307. }
  9308. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  9309. begin
  9310. hp2:=getlabelwithsym(TAsmLabel(symbol));
  9311. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  9312. MatchInstruction(hp2,A_RET,[S_NO]) then
  9313. begin
  9314. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  9315. { Change label address to that of the unconditional jump }
  9316. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  9317. TAsmLabel(symbol).DecRefs;
  9318. taicpu(hp1).opcode := A_RET;
  9319. taicpu(hp1).is_jmp := false;
  9320. taicpu(hp1).ops := taicpu(hp2).ops;
  9321. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  9322. case taicpu(hp2).ops of
  9323. 0:
  9324. taicpu(hp1).clearop(0);
  9325. 1:
  9326. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  9327. else
  9328. internalerror(2016041302);
  9329. end;
  9330. end;
  9331. {$ifndef i8086}
  9332. end
  9333. {
  9334. convert
  9335. j<c> .L1
  9336. mov 1,reg
  9337. jmp .L2
  9338. .L1
  9339. mov 0,reg
  9340. .L2
  9341. into
  9342. mov 0,reg
  9343. set<not(c)> reg
  9344. take care of alignment and that the mov 0,reg is not converted into a xor as this
  9345. would destroy the flag contents
  9346. }
  9347. else if MatchInstruction(hp1,A_MOV,[]) and
  9348. MatchOpType(taicpu(hp1),top_const,top_reg) and
  9349. {$ifdef i386}
  9350. (
  9351. { Under i386, ESI, EDI, EBP and ESP
  9352. don't have an 8-bit representation }
  9353. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  9354. ) and
  9355. {$endif i386}
  9356. (taicpu(hp1).oper[0]^.val=1) and
  9357. GetNextInstruction(hp1,hp2) and
  9358. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  9359. GetNextInstruction(hp2,hp3) and
  9360. { skip align }
  9361. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  9362. (hp3.typ=ait_label) and
  9363. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  9364. (tai_label(hp3).labsym.getrefs=1) and
  9365. GetNextInstruction(hp3,hp4) and
  9366. MatchInstruction(hp4,A_MOV,[]) and
  9367. MatchOpType(taicpu(hp4),top_const,top_reg) and
  9368. (taicpu(hp4).oper[0]^.val=0) and
  9369. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  9370. GetNextInstruction(hp4,hp5) and
  9371. (hp5.typ=ait_label) and
  9372. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  9373. (tai_label(hp5).labsym.getrefs=1) then
  9374. begin
  9375. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  9376. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  9377. { remove last label }
  9378. RemoveInstruction(hp5);
  9379. { remove second label }
  9380. RemoveInstruction(hp3);
  9381. { if align is present remove it }
  9382. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  9383. RemoveInstruction(hp3);
  9384. { remove jmp }
  9385. RemoveInstruction(hp2);
  9386. if taicpu(hp1).opsize=S_B then
  9387. RemoveInstruction(hp1)
  9388. else
  9389. taicpu(hp1).loadconst(0,0);
  9390. taicpu(hp4).opcode:=A_SETcc;
  9391. taicpu(hp4).opsize:=S_B;
  9392. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  9393. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  9394. taicpu(hp4).opercnt:=1;
  9395. taicpu(hp4).ops:=1;
  9396. taicpu(hp4).freeop(1);
  9397. RemoveCurrentP(p);
  9398. Result:=true;
  9399. exit;
  9400. end
  9401. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  9402. begin
  9403. { check for
  9404. jCC xxx
  9405. <several movs>
  9406. xxx:
  9407. Also spot:
  9408. Jcc xxx
  9409. <several movs>
  9410. jmp xxx
  9411. Change to:
  9412. <several cmovs with inverted condition>
  9413. jmp xxx
  9414. }
  9415. l:=0;
  9416. while assigned(hp1) and
  9417. CanBeCMOV(hp1) and
  9418. { stop on labels }
  9419. not(hp1.typ=ait_label) do
  9420. begin
  9421. inc(l);
  9422. hp5 := hp1;
  9423. GetNextInstruction(hp1,hp1);
  9424. end;
  9425. if assigned(hp1) then
  9426. begin
  9427. TransferUsedRegs(TmpUsedRegs);
  9428. if (
  9429. MatchInstruction(hp1, A_JMP, []) and
  9430. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  9431. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  9432. ) or
  9433. FindLabel(tasmlabel(symbol),hp1) then
  9434. begin
  9435. if (l<=4) and (l>0) then
  9436. begin
  9437. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9438. condition:=inverse_cond(taicpu(p).condition);
  9439. UpdateUsedRegs(tai(p.next));
  9440. GetNextInstruction(p,hp1);
  9441. repeat
  9442. if not Assigned(hp1) then
  9443. InternalError(2018062900);
  9444. taicpu(hp1).opcode:=A_CMOVcc;
  9445. taicpu(hp1).condition:=condition;
  9446. UpdateUsedRegs(tai(hp1.next));
  9447. GetNextInstruction(hp1,hp1);
  9448. until not(CanBeCMOV(hp1));
  9449. { Remember what hp1 is in case there's multiple aligns to get rid of }
  9450. hp2 := hp1;
  9451. repeat
  9452. if not Assigned(hp2) then
  9453. InternalError(2018062910);
  9454. case hp2.typ of
  9455. ait_label:
  9456. { What we expected - break out of the loop (it won't be a dead label at the top of
  9457. a cluster because that was optimised at an earlier stage) }
  9458. Break;
  9459. ait_align:
  9460. { Go to the next entry until a label is found (may be multiple aligns before it) }
  9461. begin
  9462. hp2 := tai(hp2.Next);
  9463. Continue;
  9464. end;
  9465. ait_instruction:
  9466. begin
  9467. if taicpu(hp2).opcode<>A_JMP then
  9468. InternalError(2018062912);
  9469. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  9470. Break;
  9471. end
  9472. else
  9473. begin
  9474. { Might be a comment or temporary allocation entry }
  9475. if not (hp2.typ in SkipInstr) then
  9476. InternalError(2018062911);
  9477. hp2 := tai(hp2.Next);
  9478. Continue;
  9479. end;
  9480. end;
  9481. until False;
  9482. { Now we can safely decrement the reference count }
  9483. tasmlabel(symbol).decrefs;
  9484. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  9485. { Remove the original jump }
  9486. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  9487. if hp2.typ=ait_instruction then
  9488. begin
  9489. p:=hp2;
  9490. Result:=True;
  9491. end
  9492. else
  9493. begin
  9494. UpdateUsedRegs(tai(hp2.next));
  9495. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  9496. { Remove the label if this is its final reference }
  9497. if (tasmlabel(symbol).getrefs=0) then
  9498. StripLabelFast(hp1);
  9499. end;
  9500. exit;
  9501. end;
  9502. end
  9503. else
  9504. begin
  9505. { check further for
  9506. jCC xxx
  9507. <several movs 1>
  9508. jmp yyy
  9509. xxx:
  9510. <several movs 2>
  9511. yyy:
  9512. }
  9513. { hp2 points to jmp yyy }
  9514. hp2:=hp1;
  9515. { skip hp1 to xxx (or an align right before it) }
  9516. GetNextInstruction(hp1, hp1);
  9517. if assigned(hp2) and
  9518. assigned(hp1) and
  9519. (l<=3) and
  9520. (hp2.typ=ait_instruction) and
  9521. (taicpu(hp2).is_jmp) and
  9522. (taicpu(hp2).condition=C_None) and
  9523. { real label and jump, no further references to the
  9524. label are allowed }
  9525. (tasmlabel(symbol).getrefs=1) and
  9526. FindLabel(tasmlabel(symbol),hp1) then
  9527. begin
  9528. l:=0;
  9529. { skip hp1 to <several moves 2> }
  9530. if (hp1.typ = ait_align) then
  9531. GetNextInstruction(hp1, hp1);
  9532. GetNextInstruction(hp1, hpmov2);
  9533. hp1 := hpmov2;
  9534. while assigned(hp1) and
  9535. CanBeCMOV(hp1) do
  9536. begin
  9537. inc(l);
  9538. hp5 := hp1;
  9539. GetNextInstruction(hp1, hp1);
  9540. end;
  9541. { hp1 points to yyy (or an align right before it) }
  9542. hp3 := hp1;
  9543. if assigned(hp1) and
  9544. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  9545. begin
  9546. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  9547. condition:=inverse_cond(taicpu(p).condition);
  9548. UpdateUsedRegs(tai(p.next));
  9549. GetNextInstruction(p,hp1);
  9550. repeat
  9551. taicpu(hp1).opcode:=A_CMOVcc;
  9552. taicpu(hp1).condition:=condition;
  9553. UpdateUsedRegs(tai(hp1.next));
  9554. GetNextInstruction(hp1,hp1);
  9555. until not(assigned(hp1)) or
  9556. not(CanBeCMOV(hp1));
  9557. condition:=inverse_cond(condition);
  9558. if GetLastInstruction(hpmov2,hp1) then
  9559. UpdateUsedRegs(tai(hp1.next));
  9560. hp1 := hpmov2;
  9561. { hp1 is now at <several movs 2> }
  9562. while Assigned(hp1) and CanBeCMOV(hp1) do
  9563. begin
  9564. taicpu(hp1).opcode:=A_CMOVcc;
  9565. taicpu(hp1).condition:=condition;
  9566. UpdateUsedRegs(tai(hp1.next));
  9567. GetNextInstruction(hp1,hp1);
  9568. end;
  9569. hp1 := p;
  9570. { Get first instruction after label }
  9571. UpdateUsedRegs(tai(hp3.next));
  9572. GetNextInstruction(hp3, p);
  9573. if assigned(p) and (hp3.typ = ait_align) then
  9574. GetNextInstruction(p, p);
  9575. { Don't dereference yet, as doing so will cause
  9576. GetNextInstruction to skip the label and
  9577. optional align marker. [Kit] }
  9578. GetNextInstruction(hp2, hp4);
  9579. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  9580. { remove jCC }
  9581. RemoveInstruction(hp1);
  9582. { Now we can safely decrement it }
  9583. tasmlabel(symbol).decrefs;
  9584. { Remove label xxx (it will have a ref of zero due to the initial check }
  9585. StripLabelFast(hp4);
  9586. { remove jmp }
  9587. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  9588. RemoveInstruction(hp2);
  9589. { As before, now we can safely decrement it }
  9590. tasmlabel(symbol).decrefs;
  9591. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  9592. if tasmlabel(symbol).getrefs = 0 then
  9593. StripLabelFast(hp3);
  9594. if Assigned(p) then
  9595. result:=true;
  9596. exit;
  9597. end;
  9598. end;
  9599. end;
  9600. end;
  9601. {$endif i8086}
  9602. end;
  9603. end;
  9604. end;
  9605. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  9606. var
  9607. hp1,hp2,hp3: tai;
  9608. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  9609. NewSize: TOpSize;
  9610. NewRegSize: TSubRegister;
  9611. Limit: TCgInt;
  9612. SwapOper: POper;
  9613. begin
  9614. result:=false;
  9615. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  9616. GetNextInstruction(p,hp1) and
  9617. (hp1.typ = ait_instruction);
  9618. if reg_and_hp1_is_instr and
  9619. (
  9620. (taicpu(hp1).opcode <> A_LEA) or
  9621. { If the LEA instruction can be converted into an arithmetic instruction,
  9622. it may be possible to then fold it. }
  9623. (
  9624. { If the flags register is in use, don't change the instruction
  9625. to an ADD otherwise this will scramble the flags. [Kit] }
  9626. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  9627. ConvertLEA(taicpu(hp1))
  9628. )
  9629. ) and
  9630. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  9631. GetNextInstruction(hp1,hp2) and
  9632. MatchInstruction(hp2,A_MOV,[]) and
  9633. (taicpu(hp2).oper[0]^.typ = top_reg) and
  9634. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  9635. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  9636. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  9637. {$ifdef i386}
  9638. { not all registers have byte size sub registers on i386 }
  9639. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  9640. {$endif i386}
  9641. (((taicpu(hp1).ops=2) and
  9642. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  9643. ((taicpu(hp1).ops=1) and
  9644. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  9645. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  9646. begin
  9647. { change movsX/movzX reg/ref, reg2
  9648. add/sub/or/... reg3/$const, reg2
  9649. mov reg2 reg/ref
  9650. to add/sub/or/... reg3/$const, reg/ref }
  9651. { by example:
  9652. movswl %si,%eax movswl %si,%eax p
  9653. decl %eax addl %edx,%eax hp1
  9654. movw %ax,%si movw %ax,%si hp2
  9655. ->
  9656. movswl %si,%eax movswl %si,%eax p
  9657. decw %eax addw %edx,%eax hp1
  9658. movw %ax,%si movw %ax,%si hp2
  9659. }
  9660. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  9661. {
  9662. ->
  9663. movswl %si,%eax movswl %si,%eax p
  9664. decw %si addw %dx,%si hp1
  9665. movw %ax,%si movw %ax,%si hp2
  9666. }
  9667. case taicpu(hp1).ops of
  9668. 1:
  9669. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  9670. 2:
  9671. begin
  9672. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  9673. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9674. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  9675. end;
  9676. else
  9677. internalerror(2008042702);
  9678. end;
  9679. {
  9680. ->
  9681. decw %si addw %dx,%si p
  9682. }
  9683. DebugMsg(SPeepholeOptimization + 'var3',p);
  9684. RemoveCurrentP(p, hp1);
  9685. RemoveInstruction(hp2);
  9686. Result := True;
  9687. Exit;
  9688. end;
  9689. if reg_and_hp1_is_instr and
  9690. (taicpu(hp1).opcode = A_MOV) and
  9691. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9692. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  9693. {$ifdef x86_64}
  9694. { check for implicit extension to 64 bit }
  9695. or
  9696. ((taicpu(p).opsize in [S_BL,S_WL]) and
  9697. (taicpu(hp1).opsize=S_Q) and
  9698. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  9699. )
  9700. {$endif x86_64}
  9701. )
  9702. then
  9703. begin
  9704. { change
  9705. movx %reg1,%reg2
  9706. mov %reg2,%reg3
  9707. dealloc %reg2
  9708. into
  9709. movx %reg,%reg3
  9710. }
  9711. TransferUsedRegs(TmpUsedRegs);
  9712. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9713. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  9714. begin
  9715. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  9716. {$ifdef x86_64}
  9717. if (taicpu(p).opsize in [S_BL,S_WL]) and
  9718. (taicpu(hp1).opsize=S_Q) then
  9719. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  9720. else
  9721. {$endif x86_64}
  9722. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  9723. RemoveInstruction(hp1);
  9724. Result := True;
  9725. Exit;
  9726. end;
  9727. end;
  9728. if reg_and_hp1_is_instr and
  9729. ((taicpu(hp1).opcode=A_MOV) or
  9730. (taicpu(hp1).opcode=A_ADD) or
  9731. (taicpu(hp1).opcode=A_SUB) or
  9732. (taicpu(hp1).opcode=A_CMP) or
  9733. (taicpu(hp1).opcode=A_OR) or
  9734. (taicpu(hp1).opcode=A_XOR) or
  9735. (taicpu(hp1).opcode=A_AND)
  9736. ) and
  9737. (taicpu(hp1).oper[1]^.typ = top_reg) then
  9738. begin
  9739. AndTest := (taicpu(hp1).opcode=A_AND) and
  9740. GetNextInstruction(hp1, hp2) and
  9741. (hp2.typ = ait_instruction) and
  9742. (
  9743. (
  9744. (taicpu(hp2).opcode=A_TEST) and
  9745. (
  9746. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  9747. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  9748. (
  9749. { If the AND and TEST instructions share a constant, this is also valid }
  9750. (taicpu(hp1).oper[0]^.typ = top_const) and
  9751. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  9752. )
  9753. ) and
  9754. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9755. ) or
  9756. (
  9757. (taicpu(hp2).opcode=A_CMP) and
  9758. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  9759. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  9760. )
  9761. );
  9762. { change
  9763. movx (oper),%reg2
  9764. and $x,%reg2
  9765. test %reg2,%reg2
  9766. dealloc %reg2
  9767. into
  9768. op %reg1,%reg3
  9769. if the second op accesses only the bits stored in reg1
  9770. }
  9771. if ((taicpu(p).oper[0]^.typ=top_reg) or
  9772. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  9773. (taicpu(hp1).oper[0]^.typ = top_const) and
  9774. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  9775. AndTest then
  9776. begin
  9777. { Check if the AND constant is in range }
  9778. case taicpu(p).opsize of
  9779. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9780. begin
  9781. NewSize := S_B;
  9782. Limit := $FF;
  9783. end;
  9784. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9785. begin
  9786. NewSize := S_W;
  9787. Limit := $FFFF;
  9788. end;
  9789. {$ifdef x86_64}
  9790. S_LQ:
  9791. begin
  9792. NewSize := S_L;
  9793. Limit := $FFFFFFFF;
  9794. end;
  9795. {$endif x86_64}
  9796. else
  9797. InternalError(2021120303);
  9798. end;
  9799. if (
  9800. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  9801. { Check for negative operands }
  9802. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  9803. ) and
  9804. GetNextInstruction(hp2,hp3) and
  9805. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  9806. (taicpu(hp3).condition in [C_E,C_NE]) then
  9807. begin
  9808. TransferUsedRegs(TmpUsedRegs);
  9809. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9810. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  9811. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  9812. begin
  9813. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  9814. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9815. taicpu(hp1).opcode := A_TEST;
  9816. taicpu(hp1).opsize := NewSize;
  9817. RemoveInstruction(hp2);
  9818. RemoveCurrentP(p, hp1);
  9819. Result:=true;
  9820. exit;
  9821. end;
  9822. end;
  9823. end;
  9824. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  9825. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  9826. (taicpu(hp1).opsize=S_B)) or
  9827. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  9828. (taicpu(hp1).opsize=S_W))
  9829. {$ifdef x86_64}
  9830. or ((taicpu(p).opsize=S_LQ) and
  9831. (taicpu(hp1).opsize=S_L))
  9832. {$endif x86_64}
  9833. ) and
  9834. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  9835. begin
  9836. { change
  9837. movx %reg1,%reg2
  9838. op %reg2,%reg3
  9839. dealloc %reg2
  9840. into
  9841. op %reg1,%reg3
  9842. if the second op accesses only the bits stored in reg1
  9843. }
  9844. TransferUsedRegs(TmpUsedRegs);
  9845. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9846. if AndTest then
  9847. begin
  9848. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9849. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9850. end
  9851. else
  9852. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9853. if not RegUsed then
  9854. begin
  9855. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  9856. if taicpu(p).oper[0]^.typ=top_reg then
  9857. begin
  9858. case taicpu(hp1).opsize of
  9859. S_B:
  9860. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  9861. S_W:
  9862. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  9863. S_L:
  9864. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  9865. else
  9866. Internalerror(2020102301);
  9867. end;
  9868. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  9869. end
  9870. else
  9871. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  9872. RemoveCurrentP(p);
  9873. if AndTest then
  9874. RemoveInstruction(hp2);
  9875. result:=true;
  9876. exit;
  9877. end;
  9878. end
  9879. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  9880. (
  9881. { Bitwise operations only }
  9882. (taicpu(hp1).opcode=A_AND) or
  9883. (taicpu(hp1).opcode=A_TEST) or
  9884. (
  9885. (taicpu(hp1).oper[0]^.typ = top_const) and
  9886. (
  9887. (taicpu(hp1).opcode=A_OR) or
  9888. (taicpu(hp1).opcode=A_XOR)
  9889. )
  9890. )
  9891. ) and
  9892. (
  9893. (taicpu(hp1).oper[0]^.typ = top_const) or
  9894. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  9895. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  9896. ) then
  9897. begin
  9898. { change
  9899. movx %reg2,%reg2
  9900. op const,%reg2
  9901. into
  9902. op const,%reg2 (smaller version)
  9903. movx %reg2,%reg2
  9904. also change
  9905. movx %reg1,%reg2
  9906. and/test (oper),%reg2
  9907. dealloc %reg2
  9908. into
  9909. and/test (oper),%reg1
  9910. }
  9911. case taicpu(p).opsize of
  9912. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9913. begin
  9914. NewSize := S_B;
  9915. NewRegSize := R_SUBL;
  9916. Limit := $FF;
  9917. end;
  9918. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9919. begin
  9920. NewSize := S_W;
  9921. NewRegSize := R_SUBW;
  9922. Limit := $FFFF;
  9923. end;
  9924. {$ifdef x86_64}
  9925. S_LQ:
  9926. begin
  9927. NewSize := S_L;
  9928. NewRegSize := R_SUBD;
  9929. Limit := $FFFFFFFF;
  9930. end;
  9931. {$endif x86_64}
  9932. else
  9933. Internalerror(2021120302);
  9934. end;
  9935. TransferUsedRegs(TmpUsedRegs);
  9936. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9937. if AndTest then
  9938. begin
  9939. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9940. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  9941. end
  9942. else
  9943. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  9944. if
  9945. (
  9946. (taicpu(p).opcode = A_MOVZX) and
  9947. (
  9948. (taicpu(hp1).opcode=A_AND) or
  9949. (taicpu(hp1).opcode=A_TEST)
  9950. ) and
  9951. not (
  9952. { If both are references, then the final instruction will have
  9953. both operands as references, which is not allowed }
  9954. (taicpu(p).oper[0]^.typ = top_ref) and
  9955. (taicpu(hp1).oper[0]^.typ = top_ref)
  9956. ) and
  9957. not RegUsed
  9958. ) or
  9959. (
  9960. (
  9961. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  9962. not RegUsed
  9963. ) and
  9964. (taicpu(p).oper[0]^.typ = top_reg) and
  9965. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  9966. (taicpu(hp1).oper[0]^.typ = top_const) and
  9967. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  9968. ) then
  9969. begin
  9970. {$if defined(i386) or defined(i8086)}
  9971. { If the target size is 8-bit, make sure we can actually encode it }
  9972. 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
  9973. Exit;
  9974. {$endif i386 or i8086}
  9975. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  9976. taicpu(hp1).opsize := NewSize;
  9977. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  9978. if AndTest then
  9979. begin
  9980. RemoveInstruction(hp2);
  9981. if not RegUsed then
  9982. begin
  9983. taicpu(hp1).opcode := A_TEST;
  9984. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  9985. begin
  9986. { Make sure the reference is the second operand }
  9987. SwapOper := taicpu(hp1).oper[0];
  9988. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  9989. taicpu(hp1).oper[1] := SwapOper;
  9990. end;
  9991. end;
  9992. end;
  9993. case taicpu(hp1).oper[0]^.typ of
  9994. top_reg:
  9995. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  9996. top_const:
  9997. { For the AND/TEST case }
  9998. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  9999. else
  10000. ;
  10001. end;
  10002. if RegUsed then
  10003. begin
  10004. AsmL.Remove(p);
  10005. AsmL.InsertAfter(p, hp1);
  10006. p := hp1;
  10007. end
  10008. else
  10009. RemoveCurrentP(p, hp1);
  10010. result:=true;
  10011. exit;
  10012. end;
  10013. end;
  10014. end;
  10015. if reg_and_hp1_is_instr and
  10016. (taicpu(p).oper[0]^.typ = top_reg) and
  10017. (
  10018. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  10019. ) and
  10020. (taicpu(hp1).oper[0]^.typ = top_const) and
  10021. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10022. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10023. { Minimum shift value allowed is the bit difference between the sizes }
  10024. (taicpu(hp1).oper[0]^.val >=
  10025. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10026. 8 * (
  10027. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10028. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10029. )
  10030. ) then
  10031. begin
  10032. { For:
  10033. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10034. shl/sal ##, %reg1
  10035. Remove the movsx/movzx instruction if the shift overwrites the
  10036. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10037. }
  10038. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10039. RemoveCurrentP(p, hp1);
  10040. Result := True;
  10041. Exit;
  10042. end
  10043. else if reg_and_hp1_is_instr and
  10044. (taicpu(p).oper[0]^.typ = top_reg) and
  10045. (
  10046. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10047. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10048. ) and
  10049. (taicpu(hp1).oper[0]^.typ = top_const) and
  10050. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10051. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10052. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10053. (taicpu(hp1).oper[0]^.val <
  10054. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10055. 8 * (
  10056. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10057. )
  10058. ) then
  10059. begin
  10060. { For:
  10061. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10062. sar ##, %reg1 shr ##, %reg1
  10063. Move the shift to before the movx instruction if the shift value
  10064. is not too large.
  10065. }
  10066. asml.Remove(hp1);
  10067. asml.InsertBefore(hp1, p);
  10068. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10069. case taicpu(p).opsize of
  10070. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  10071. taicpu(hp1).opsize := S_B;
  10072. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  10073. taicpu(hp1).opsize := S_W;
  10074. {$ifdef x86_64}
  10075. S_LQ:
  10076. taicpu(hp1).opsize := S_L;
  10077. {$endif}
  10078. else
  10079. InternalError(2020112401);
  10080. end;
  10081. if (taicpu(hp1).opcode = A_SHR) then
  10082. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  10083. else
  10084. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  10085. Result := True;
  10086. end;
  10087. if reg_and_hp1_is_instr and
  10088. (taicpu(p).oper[0]^.typ = top_reg) and
  10089. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10090. (
  10091. (taicpu(hp1).opcode = taicpu(p).opcode)
  10092. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  10093. {$ifdef x86_64}
  10094. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  10095. {$endif x86_64}
  10096. ) then
  10097. begin
  10098. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10099. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  10100. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10101. begin
  10102. {
  10103. For example:
  10104. movzbw %al,%ax
  10105. movzwl %ax,%eax
  10106. Compress into:
  10107. movzbl %al,%eax
  10108. }
  10109. RegUsed := False;
  10110. case taicpu(p).opsize of
  10111. S_BW:
  10112. case taicpu(hp1).opsize of
  10113. S_WL:
  10114. begin
  10115. taicpu(p).opsize := S_BL;
  10116. RegUsed := True;
  10117. end;
  10118. {$ifdef x86_64}
  10119. S_WQ:
  10120. begin
  10121. if taicpu(p).opcode = A_MOVZX then
  10122. begin
  10123. taicpu(p).opsize := S_BL;
  10124. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10125. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10126. end
  10127. else
  10128. taicpu(p).opsize := S_BQ;
  10129. RegUsed := True;
  10130. end;
  10131. {$endif x86_64}
  10132. else
  10133. ;
  10134. end;
  10135. {$ifdef x86_64}
  10136. S_BL:
  10137. case taicpu(hp1).opsize of
  10138. S_LQ:
  10139. begin
  10140. if taicpu(p).opcode = A_MOVZX then
  10141. begin
  10142. taicpu(p).opsize := S_BL;
  10143. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10144. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10145. end
  10146. else
  10147. taicpu(p).opsize := S_BQ;
  10148. RegUsed := True;
  10149. end;
  10150. else
  10151. ;
  10152. end;
  10153. S_WL:
  10154. case taicpu(hp1).opsize of
  10155. S_LQ:
  10156. begin
  10157. if taicpu(p).opcode = A_MOVZX then
  10158. begin
  10159. taicpu(p).opsize := S_WL;
  10160. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10161. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10162. end
  10163. else
  10164. taicpu(p).opsize := S_WQ;
  10165. RegUsed := True;
  10166. end;
  10167. else
  10168. ;
  10169. end;
  10170. {$endif x86_64}
  10171. else
  10172. ;
  10173. end;
  10174. if RegUsed then
  10175. begin
  10176. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  10177. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  10178. RemoveInstruction(hp1);
  10179. Result := True;
  10180. Exit;
  10181. end;
  10182. end;
  10183. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  10184. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  10185. GetNextInstruction(hp1, hp2) and
  10186. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  10187. (
  10188. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  10189. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  10190. {$ifdef x86_64}
  10191. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  10192. {$endif x86_64}
  10193. ) and
  10194. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  10195. (
  10196. (
  10197. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10198. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10199. ) or
  10200. (
  10201. { Only allow the operands in reverse order for TEST instructions }
  10202. (taicpu(hp2).opcode = A_TEST) and
  10203. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10204. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  10205. )
  10206. ) then
  10207. begin
  10208. {
  10209. For example:
  10210. movzbl %al,%eax
  10211. movzbl (ref),%edx
  10212. andl %edx,%eax
  10213. (%edx deallocated)
  10214. Change to:
  10215. andb (ref),%al
  10216. movzbl %al,%eax
  10217. Rules are:
  10218. - First two instructions have the same opcode and opsize
  10219. - First instruction's operands are the same super-register
  10220. - Second instruction operates on a different register
  10221. - Third instruction is AND, OR, XOR or TEST
  10222. - Third instruction's operands are the destination registers of the first two instructions
  10223. - Third instruction writes to the destination register of the first instruction (except with TEST)
  10224. - Second instruction's destination register is deallocated afterwards
  10225. }
  10226. TransferUsedRegs(TmpUsedRegs);
  10227. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10228. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10229. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  10230. begin
  10231. case taicpu(p).opsize of
  10232. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10233. NewSize := S_B;
  10234. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10235. NewSize := S_W;
  10236. {$ifdef x86_64}
  10237. S_LQ:
  10238. NewSize := S_L;
  10239. {$endif x86_64}
  10240. else
  10241. InternalError(2021120301);
  10242. end;
  10243. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  10244. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  10245. taicpu(hp2).opsize := NewSize;
  10246. RemoveInstruction(hp1);
  10247. { With TEST, it's best to keep the MOVX instruction at the top }
  10248. if (taicpu(hp2).opcode <> A_TEST) then
  10249. begin
  10250. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  10251. asml.Remove(p);
  10252. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  10253. asml.InsertAfter(p, hp2);
  10254. p := hp2;
  10255. end
  10256. else
  10257. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  10258. Result := True;
  10259. Exit;
  10260. end;
  10261. end;
  10262. end;
  10263. if taicpu(p).opcode=A_MOVZX then
  10264. begin
  10265. { removes superfluous And's after movzx's }
  10266. if reg_and_hp1_is_instr and
  10267. (taicpu(hp1).opcode = A_AND) and
  10268. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10269. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  10270. {$ifdef x86_64}
  10271. { check for implicit extension to 64 bit }
  10272. or
  10273. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10274. (taicpu(hp1).opsize=S_Q) and
  10275. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  10276. )
  10277. {$endif x86_64}
  10278. )
  10279. then
  10280. begin
  10281. case taicpu(p).opsize Of
  10282. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10283. if (taicpu(hp1).oper[0]^.val = $ff) then
  10284. begin
  10285. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  10286. RemoveInstruction(hp1);
  10287. Result:=true;
  10288. exit;
  10289. end;
  10290. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10291. if (taicpu(hp1).oper[0]^.val = $ffff) then
  10292. begin
  10293. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  10294. RemoveInstruction(hp1);
  10295. Result:=true;
  10296. exit;
  10297. end;
  10298. {$ifdef x86_64}
  10299. S_LQ:
  10300. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  10301. begin
  10302. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  10303. RemoveInstruction(hp1);
  10304. Result:=true;
  10305. exit;
  10306. end;
  10307. {$endif x86_64}
  10308. else
  10309. ;
  10310. end;
  10311. { we cannot get rid of the and, but can we get rid of the movz ?}
  10312. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  10313. begin
  10314. case taicpu(p).opsize Of
  10315. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10316. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  10317. begin
  10318. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  10319. RemoveCurrentP(p,hp1);
  10320. Result:=true;
  10321. exit;
  10322. end;
  10323. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10324. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  10325. begin
  10326. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  10327. RemoveCurrentP(p,hp1);
  10328. Result:=true;
  10329. exit;
  10330. end;
  10331. {$ifdef x86_64}
  10332. S_LQ:
  10333. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  10334. begin
  10335. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  10336. RemoveCurrentP(p,hp1);
  10337. Result:=true;
  10338. exit;
  10339. end;
  10340. {$endif x86_64}
  10341. else
  10342. ;
  10343. end;
  10344. end;
  10345. end;
  10346. { changes some movzx constructs to faster synonyms (all examples
  10347. are given with eax/ax, but are also valid for other registers)}
  10348. if MatchOpType(taicpu(p),top_reg,top_reg) then
  10349. begin
  10350. case taicpu(p).opsize of
  10351. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  10352. (the machine code is equivalent to movzbl %al,%eax), but the
  10353. code generator still generates that assembler instruction and
  10354. it is silently converted. This should probably be checked.
  10355. [Kit] }
  10356. S_BW:
  10357. begin
  10358. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10359. (
  10360. not IsMOVZXAcceptable
  10361. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  10362. or (
  10363. (cs_opt_size in current_settings.optimizerswitches) and
  10364. (taicpu(p).oper[1]^.reg = NR_AX)
  10365. )
  10366. ) then
  10367. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  10368. begin
  10369. DebugMsg(SPeepholeOptimization + 'var7',p);
  10370. taicpu(p).opcode := A_AND;
  10371. taicpu(p).changeopsize(S_W);
  10372. taicpu(p).loadConst(0,$ff);
  10373. Result := True;
  10374. end
  10375. else if not IsMOVZXAcceptable and
  10376. GetNextInstruction(p, hp1) and
  10377. (tai(hp1).typ = ait_instruction) and
  10378. (taicpu(hp1).opcode = A_AND) and
  10379. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10380. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10381. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  10382. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  10383. begin
  10384. DebugMsg(SPeepholeOptimization + 'var8',p);
  10385. taicpu(p).opcode := A_MOV;
  10386. taicpu(p).changeopsize(S_W);
  10387. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  10388. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10389. Result := True;
  10390. end;
  10391. end;
  10392. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  10393. S_BL:
  10394. begin
  10395. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  10396. (
  10397. not IsMOVZXAcceptable
  10398. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  10399. or (
  10400. (cs_opt_size in current_settings.optimizerswitches) and
  10401. (taicpu(p).oper[1]^.reg = NR_EAX)
  10402. )
  10403. ) then
  10404. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  10405. begin
  10406. DebugMsg(SPeepholeOptimization + 'var9',p);
  10407. taicpu(p).opcode := A_AND;
  10408. taicpu(p).changeopsize(S_L);
  10409. taicpu(p).loadConst(0,$ff);
  10410. Result := True;
  10411. end
  10412. else if not IsMOVZXAcceptable and
  10413. GetNextInstruction(p, hp1) and
  10414. (tai(hp1).typ = ait_instruction) and
  10415. (taicpu(hp1).opcode = A_AND) and
  10416. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10417. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10418. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  10419. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  10420. begin
  10421. DebugMsg(SPeepholeOptimization + 'var10',p);
  10422. taicpu(p).opcode := A_MOV;
  10423. taicpu(p).changeopsize(S_L);
  10424. { do not use R_SUBWHOLE
  10425. as movl %rdx,%eax
  10426. is invalid in assembler PM }
  10427. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10428. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10429. Result := True;
  10430. end;
  10431. end;
  10432. {$endif i8086}
  10433. S_WL:
  10434. if not IsMOVZXAcceptable then
  10435. begin
  10436. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  10437. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  10438. begin
  10439. DebugMsg(SPeepholeOptimization + 'var11',p);
  10440. taicpu(p).opcode := A_AND;
  10441. taicpu(p).changeopsize(S_L);
  10442. taicpu(p).loadConst(0,$ffff);
  10443. Result := True;
  10444. end
  10445. else if GetNextInstruction(p, hp1) and
  10446. (tai(hp1).typ = ait_instruction) and
  10447. (taicpu(hp1).opcode = A_AND) and
  10448. (taicpu(hp1).oper[0]^.typ = top_const) and
  10449. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10450. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10451. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  10452. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  10453. begin
  10454. DebugMsg(SPeepholeOptimization + 'var12',p);
  10455. taicpu(p).opcode := A_MOV;
  10456. taicpu(p).changeopsize(S_L);
  10457. { do not use R_SUBWHOLE
  10458. as movl %rdx,%eax
  10459. is invalid in assembler PM }
  10460. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  10461. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10462. Result := True;
  10463. end;
  10464. end;
  10465. else
  10466. InternalError(2017050705);
  10467. end;
  10468. end
  10469. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  10470. begin
  10471. if GetNextInstruction(p, hp1) and
  10472. (tai(hp1).typ = ait_instruction) and
  10473. (taicpu(hp1).opcode = A_AND) and
  10474. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10475. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  10476. begin
  10477. //taicpu(p).opcode := A_MOV;
  10478. case taicpu(p).opsize Of
  10479. S_BL:
  10480. begin
  10481. DebugMsg(SPeepholeOptimization + 'var13',p);
  10482. taicpu(hp1).changeopsize(S_L);
  10483. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10484. end;
  10485. S_WL:
  10486. begin
  10487. DebugMsg(SPeepholeOptimization + 'var14',p);
  10488. taicpu(hp1).changeopsize(S_L);
  10489. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  10490. end;
  10491. S_BW:
  10492. begin
  10493. DebugMsg(SPeepholeOptimization + 'var15',p);
  10494. taicpu(hp1).changeopsize(S_W);
  10495. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  10496. end;
  10497. else
  10498. Internalerror(2017050704)
  10499. end;
  10500. Result := True;
  10501. end;
  10502. end;
  10503. end;
  10504. end;
  10505. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  10506. var
  10507. hp1, hp2 : tai;
  10508. MaskLength : Cardinal;
  10509. MaskedBits : TCgInt;
  10510. ActiveReg : TRegister;
  10511. begin
  10512. Result:=false;
  10513. { There are no optimisations for reference targets }
  10514. if (taicpu(p).oper[1]^.typ <> top_reg) then
  10515. Exit;
  10516. while GetNextInstruction(p, hp1) and
  10517. (hp1.typ = ait_instruction) do
  10518. begin
  10519. if (taicpu(p).oper[0]^.typ = top_const) then
  10520. begin
  10521. case taicpu(hp1).opcode of
  10522. A_AND:
  10523. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10524. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10525. { the second register must contain the first one, so compare their subreg types }
  10526. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  10527. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  10528. { change
  10529. and const1, reg
  10530. and const2, reg
  10531. to
  10532. and (const1 and const2), reg
  10533. }
  10534. begin
  10535. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  10536. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  10537. RemoveCurrentP(p, hp1);
  10538. Result:=true;
  10539. exit;
  10540. end;
  10541. A_CMP:
  10542. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  10543. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  10544. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10545. { Just check that the condition on the next instruction is compatible }
  10546. GetNextInstruction(hp1, hp2) and
  10547. (hp2.typ = ait_instruction) and
  10548. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  10549. then
  10550. { change
  10551. and 2^n, reg
  10552. cmp 2^n, reg
  10553. j(c) / set(c) / cmov(c) (c is equal or not equal)
  10554. to
  10555. and 2^n, reg
  10556. test reg, reg
  10557. j(~c) / set(~c) / cmov(~c)
  10558. }
  10559. begin
  10560. { Keep TEST instruction in, rather than remove it, because
  10561. it may trigger other optimisations such as MovAndTest2Test }
  10562. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  10563. taicpu(hp1).opcode := A_TEST;
  10564. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  10565. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  10566. Result := True;
  10567. Exit;
  10568. end;
  10569. A_MOVZX:
  10570. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10571. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  10572. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  10573. (
  10574. (
  10575. (taicpu(p).opsize=S_W) and
  10576. (taicpu(hp1).opsize=S_BW)
  10577. ) or
  10578. (
  10579. (taicpu(p).opsize=S_L) and
  10580. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  10581. )
  10582. {$ifdef x86_64}
  10583. or
  10584. (
  10585. (taicpu(p).opsize=S_Q) and
  10586. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  10587. )
  10588. {$endif x86_64}
  10589. ) then
  10590. begin
  10591. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10592. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  10593. ) or
  10594. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10595. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  10596. then
  10597. begin
  10598. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  10599. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  10600. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  10601. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  10602. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  10603. }
  10604. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  10605. RemoveInstruction(hp1);
  10606. { See if there are other optimisations possible }
  10607. Continue;
  10608. end;
  10609. end;
  10610. A_SHL:
  10611. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10612. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  10613. begin
  10614. {$ifopt R+}
  10615. {$define RANGE_WAS_ON}
  10616. {$R-}
  10617. {$endif}
  10618. { get length of potential and mask }
  10619. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  10620. { really a mask? }
  10621. {$ifdef RANGE_WAS_ON}
  10622. {$R+}
  10623. {$endif}
  10624. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  10625. { unmasked part shifted out? }
  10626. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  10627. begin
  10628. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  10629. RemoveCurrentP(p, hp1);
  10630. Result:=true;
  10631. exit;
  10632. end;
  10633. end;
  10634. A_SHR:
  10635. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  10636. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10637. (taicpu(hp1).oper[0]^.val <= 63) then
  10638. begin
  10639. { Does SHR combined with the AND cover all the bits?
  10640. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  10641. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  10642. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  10643. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  10644. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  10645. begin
  10646. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  10647. RemoveCurrentP(p, hp1);
  10648. Result := True;
  10649. Exit;
  10650. end;
  10651. end;
  10652. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10653. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10654. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10655. begin
  10656. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10657. (
  10658. (
  10659. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  10660. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  10661. ) or (
  10662. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  10663. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  10664. {$ifdef x86_64}
  10665. ) or (
  10666. (taicpu(hp1).opsize = S_LQ) and
  10667. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  10668. {$endif x86_64}
  10669. )
  10670. ) then
  10671. begin
  10672. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  10673. begin
  10674. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  10675. RemoveInstruction(hp1);
  10676. { See if there are other optimisations possible }
  10677. Continue;
  10678. end;
  10679. { The super-registers are the same though.
  10680. Note that this change by itself doesn't improve
  10681. code speed, but it opens up other optimisations. }
  10682. {$ifdef x86_64}
  10683. { Convert 64-bit register to 32-bit }
  10684. case taicpu(hp1).opsize of
  10685. S_BQ:
  10686. begin
  10687. taicpu(hp1).opsize := S_BL;
  10688. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10689. end;
  10690. S_WQ:
  10691. begin
  10692. taicpu(hp1).opsize := S_WL;
  10693. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  10694. end
  10695. else
  10696. ;
  10697. end;
  10698. {$endif x86_64}
  10699. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  10700. taicpu(hp1).opcode := A_MOVZX;
  10701. { See if there are other optimisations possible }
  10702. Continue;
  10703. end;
  10704. end;
  10705. else
  10706. ;
  10707. end;
  10708. end
  10709. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  10710. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  10711. begin
  10712. {$ifdef x86_64}
  10713. if (taicpu(p).opsize = S_Q) then
  10714. begin
  10715. { Never necessary }
  10716. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  10717. RemoveCurrentP(p, hp1);
  10718. Result := True;
  10719. Exit;
  10720. end;
  10721. {$endif x86_64}
  10722. { Forward check to determine necessity of and %reg,%reg }
  10723. TransferUsedRegs(TmpUsedRegs);
  10724. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10725. { Saves on a bunch of dereferences }
  10726. ActiveReg := taicpu(p).oper[1]^.reg;
  10727. case taicpu(hp1).opcode of
  10728. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  10729. if (
  10730. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10731. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10732. ) and
  10733. (
  10734. (taicpu(hp1).opcode <> A_MOV) or
  10735. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  10736. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  10737. ) and
  10738. not (
  10739. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  10740. (taicpu(hp1).opcode = A_MOV) and
  10741. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  10742. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  10743. ) and
  10744. (
  10745. (
  10746. (taicpu(hp1).oper[0]^.typ = top_reg) and
  10747. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  10748. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  10749. ) or
  10750. (
  10751. {$ifdef x86_64}
  10752. (
  10753. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  10754. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  10755. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  10756. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  10757. ) and
  10758. {$endif x86_64}
  10759. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  10760. )
  10761. ) then
  10762. begin
  10763. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  10764. RemoveCurrentP(p, hp1);
  10765. Result := True;
  10766. Exit;
  10767. end;
  10768. A_ADD,
  10769. A_AND,
  10770. A_BSF,
  10771. A_BSR,
  10772. A_BTC,
  10773. A_BTR,
  10774. A_BTS,
  10775. A_OR,
  10776. A_SUB,
  10777. A_XOR:
  10778. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  10779. if (
  10780. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10781. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10782. ) and
  10783. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  10784. begin
  10785. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  10786. RemoveCurrentP(p, hp1);
  10787. Result := True;
  10788. Exit;
  10789. end;
  10790. A_CMP,
  10791. A_TEST:
  10792. if (
  10793. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  10794. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  10795. ) and
  10796. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  10797. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  10798. begin
  10799. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  10800. RemoveCurrentP(p, hp1);
  10801. Result := True;
  10802. Exit;
  10803. end;
  10804. A_BSWAP,
  10805. A_NEG,
  10806. A_NOT:
  10807. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  10808. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  10809. begin
  10810. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  10811. RemoveCurrentP(p, hp1);
  10812. Result := True;
  10813. Exit;
  10814. end;
  10815. else
  10816. ;
  10817. end;
  10818. end;
  10819. if (taicpu(hp1).is_jmp) and
  10820. (taicpu(hp1).opcode<>A_JMP) and
  10821. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  10822. begin
  10823. { change
  10824. and x, reg
  10825. jxx
  10826. to
  10827. test x, reg
  10828. jxx
  10829. if reg is deallocated before the
  10830. jump, but only if it's a conditional jump (PFV)
  10831. }
  10832. taicpu(p).opcode := A_TEST;
  10833. Exit;
  10834. end;
  10835. Break;
  10836. end;
  10837. { Lone AND tests }
  10838. if (taicpu(p).oper[0]^.typ = top_const) then
  10839. begin
  10840. {
  10841. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  10842. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  10843. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  10844. }
  10845. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  10846. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  10847. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  10848. begin
  10849. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  10850. if taicpu(p).opsize = S_L then
  10851. begin
  10852. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  10853. Result := True;
  10854. end;
  10855. end;
  10856. end;
  10857. { Backward check to determine necessity of and %reg,%reg }
  10858. if (taicpu(p).oper[0]^.typ = top_reg) and
  10859. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  10860. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10861. GetLastInstruction(p, hp2) and
  10862. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  10863. { Check size of adjacent instruction to determine if the AND is
  10864. effectively a null operation }
  10865. (
  10866. (taicpu(p).opsize = taicpu(hp2).opsize) or
  10867. { Note: Don't include S_Q }
  10868. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  10869. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  10870. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  10871. ) then
  10872. begin
  10873. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  10874. { If GetNextInstruction returned False, hp1 will be nil }
  10875. RemoveCurrentP(p, hp1);
  10876. Result := True;
  10877. Exit;
  10878. end;
  10879. end;
  10880. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  10881. var
  10882. hp1: tai; NewRef: TReference;
  10883. { This entire nested function is used in an if-statement below, but we
  10884. want to avoid all the used reg transfers and GetNextInstruction calls
  10885. until we really have to check }
  10886. function MemRegisterNotUsedLater: Boolean; inline;
  10887. var
  10888. hp2: tai;
  10889. begin
  10890. TransferUsedRegs(TmpUsedRegs);
  10891. hp2 := p;
  10892. repeat
  10893. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  10894. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  10895. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  10896. end;
  10897. begin
  10898. Result := False;
  10899. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  10900. Exit;
  10901. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  10902. begin
  10903. { Change:
  10904. add %reg2,%reg1
  10905. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  10906. To:
  10907. mov/s/z #(%reg1,%reg2),%reg1
  10908. }
  10909. if MatchOpType(taicpu(p), top_reg, top_reg) and
  10910. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  10911. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  10912. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  10913. (
  10914. (
  10915. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  10916. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  10917. { r/esp cannot be an index }
  10918. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  10919. ) or (
  10920. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  10921. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  10922. )
  10923. ) and (
  10924. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  10925. (
  10926. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  10927. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  10928. MemRegisterNotUsedLater
  10929. )
  10930. ) then
  10931. begin
  10932. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  10933. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  10934. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  10935. RemoveCurrentp(p, hp1);
  10936. Result := True;
  10937. Exit;
  10938. end;
  10939. { Change:
  10940. addl/q $x,%reg1
  10941. movl/q %reg1,%reg2
  10942. To:
  10943. leal/q $x(%reg1),%reg2
  10944. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  10945. Breaks the dependency chain.
  10946. }
  10947. if MatchOpType(taicpu(p),top_const,top_reg) and
  10948. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  10949. (taicpu(hp1).oper[1]^.typ = top_reg) and
  10950. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  10951. (
  10952. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  10953. not (cs_opt_size in current_settings.optimizerswitches) or
  10954. (
  10955. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  10956. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  10957. )
  10958. ) then
  10959. begin
  10960. { Change the MOV instruction to a LEA instruction, and update the
  10961. first operand }
  10962. reference_reset(NewRef, 1, []);
  10963. NewRef.base := taicpu(p).oper[1]^.reg;
  10964. NewRef.scalefactor := 1;
  10965. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  10966. taicpu(hp1).opcode := A_LEA;
  10967. taicpu(hp1).loadref(0, NewRef);
  10968. TransferUsedRegs(TmpUsedRegs);
  10969. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10970. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  10971. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  10972. begin
  10973. { Move what is now the LEA instruction to before the SUB instruction }
  10974. Asml.Remove(hp1);
  10975. Asml.InsertBefore(hp1, p);
  10976. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  10977. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  10978. p := hp1;
  10979. end
  10980. else
  10981. begin
  10982. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  10983. RemoveCurrentP(p, hp1);
  10984. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  10985. end;
  10986. Result := True;
  10987. end;
  10988. end;
  10989. end;
  10990. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  10991. var
  10992. SubReg: TSubRegister;
  10993. begin
  10994. Result:=false;
  10995. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  10996. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  10997. with taicpu(p).oper[0]^.ref^ do
  10998. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  10999. begin
  11000. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  11001. begin
  11002. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  11003. taicpu(p).opcode := A_ADD;
  11004. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  11005. Result := True;
  11006. end
  11007. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  11008. begin
  11009. if (base <> NR_NO) then
  11010. begin
  11011. if (scalefactor <= 1) then
  11012. begin
  11013. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  11014. taicpu(p).opcode := A_ADD;
  11015. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  11016. Result := True;
  11017. end;
  11018. end
  11019. else
  11020. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  11021. if (scalefactor in [2, 4, 8]) then
  11022. begin
  11023. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  11024. taicpu(p).loadconst(0, BsrByte(scalefactor));
  11025. taicpu(p).opcode := A_SHL;
  11026. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  11027. Result := True;
  11028. end;
  11029. end;
  11030. end;
  11031. end;
  11032. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  11033. var
  11034. hp1: tai; NewRef: TReference;
  11035. begin
  11036. { Change:
  11037. subl/q $x,%reg1
  11038. movl/q %reg1,%reg2
  11039. To:
  11040. leal/q $-x(%reg1),%reg2
  11041. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11042. Breaks the dependency chain and potentially permits the removal of
  11043. a CMP instruction if one follows.
  11044. }
  11045. Result := False;
  11046. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  11047. MatchOpType(taicpu(p),top_const,top_reg) and
  11048. GetNextInstruction(p, hp1) and
  11049. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11050. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11051. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11052. (
  11053. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  11054. not (cs_opt_size in current_settings.optimizerswitches) or
  11055. (
  11056. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11057. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11058. )
  11059. ) then
  11060. begin
  11061. { Change the MOV instruction to a LEA instruction, and update the
  11062. first operand }
  11063. reference_reset(NewRef, 1, []);
  11064. NewRef.base := taicpu(p).oper[1]^.reg;
  11065. NewRef.scalefactor := 1;
  11066. NewRef.offset := -taicpu(p).oper[0]^.val;
  11067. taicpu(hp1).opcode := A_LEA;
  11068. taicpu(hp1).loadref(0, NewRef);
  11069. TransferUsedRegs(TmpUsedRegs);
  11070. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11071. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11072. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11073. begin
  11074. { Move what is now the LEA instruction to before the SUB instruction }
  11075. Asml.Remove(hp1);
  11076. Asml.InsertBefore(hp1, p);
  11077. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  11078. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  11079. p := hp1;
  11080. end
  11081. else
  11082. begin
  11083. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11084. RemoveCurrentP(p, hp1);
  11085. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  11086. end;
  11087. Result := True;
  11088. end;
  11089. end;
  11090. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  11091. begin
  11092. { we can skip all instructions not messing with the stack pointer }
  11093. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  11094. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  11095. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  11096. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  11097. ({(taicpu(hp1).ops=0) or }
  11098. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  11099. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  11100. ) and }
  11101. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  11102. )
  11103. ) do
  11104. GetNextInstruction(hp1,hp1);
  11105. Result:=assigned(hp1);
  11106. end;
  11107. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  11108. var
  11109. hp1, hp2, hp3, hp4, hp5: tai;
  11110. begin
  11111. Result:=false;
  11112. hp5:=nil;
  11113. { replace
  11114. leal(q) x(<stackpointer>),<stackpointer>
  11115. call procname
  11116. leal(q) -x(<stackpointer>),<stackpointer>
  11117. ret
  11118. by
  11119. jmp procname
  11120. but do it only on level 4 because it destroys stack back traces
  11121. }
  11122. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11123. MatchOpType(taicpu(p),top_ref,top_reg) and
  11124. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11125. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  11126. { the -8 or -24 are not required, but bail out early if possible,
  11127. higher values are unlikely }
  11128. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  11129. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  11130. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  11131. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  11132. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11133. GetNextInstruction(p, hp1) and
  11134. { Take a copy of hp1 }
  11135. SetAndTest(hp1, hp4) and
  11136. { trick to skip label }
  11137. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11138. SkipSimpleInstructions(hp1) and
  11139. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11140. GetNextInstruction(hp1, hp2) and
  11141. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  11142. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  11143. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  11144. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  11145. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  11146. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  11147. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  11148. { Segment register will be NR_NO }
  11149. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  11150. GetNextInstruction(hp2, hp3) and
  11151. { trick to skip label }
  11152. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11153. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11154. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11155. SetAndTest(hp3,hp5) and
  11156. GetNextInstruction(hp3,hp3) and
  11157. MatchInstruction(hp3,A_RET,[S_NO])
  11158. )
  11159. ) and
  11160. (taicpu(hp3).ops=0) then
  11161. begin
  11162. taicpu(hp1).opcode := A_JMP;
  11163. taicpu(hp1).is_jmp := true;
  11164. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  11165. RemoveCurrentP(p, hp4);
  11166. RemoveInstruction(hp2);
  11167. RemoveInstruction(hp3);
  11168. if Assigned(hp5) then
  11169. begin
  11170. AsmL.Remove(hp5);
  11171. ASmL.InsertBefore(hp5,hp1)
  11172. end;
  11173. Result:=true;
  11174. end;
  11175. end;
  11176. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  11177. {$ifdef x86_64}
  11178. var
  11179. hp1, hp2, hp3, hp4, hp5: tai;
  11180. {$endif x86_64}
  11181. begin
  11182. Result:=false;
  11183. {$ifdef x86_64}
  11184. hp5:=nil;
  11185. { replace
  11186. push %rax
  11187. call procname
  11188. pop %rcx
  11189. ret
  11190. by
  11191. jmp procname
  11192. but do it only on level 4 because it destroys stack back traces
  11193. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  11194. for all supported calling conventions
  11195. }
  11196. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11197. MatchOpType(taicpu(p),top_reg) and
  11198. (taicpu(p).oper[0]^.reg=NR_RAX) and
  11199. GetNextInstruction(p, hp1) and
  11200. { Take a copy of hp1 }
  11201. SetAndTest(hp1, hp4) and
  11202. { trick to skip label }
  11203. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  11204. SkipSimpleInstructions(hp1) and
  11205. MatchInstruction(hp1,A_CALL,[S_NO]) and
  11206. GetNextInstruction(hp1, hp2) and
  11207. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  11208. MatchOpType(taicpu(hp2),top_reg) and
  11209. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  11210. GetNextInstruction(hp2, hp3) and
  11211. { trick to skip label }
  11212. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  11213. (MatchInstruction(hp3,A_RET,[S_NO]) or
  11214. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  11215. SetAndTest(hp3,hp5) and
  11216. GetNextInstruction(hp3,hp3) and
  11217. MatchInstruction(hp3,A_RET,[S_NO])
  11218. )
  11219. ) and
  11220. (taicpu(hp3).ops=0) then
  11221. begin
  11222. taicpu(hp1).opcode := A_JMP;
  11223. taicpu(hp1).is_jmp := true;
  11224. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  11225. RemoveCurrentP(p, hp4);
  11226. RemoveInstruction(hp2);
  11227. RemoveInstruction(hp3);
  11228. if Assigned(hp5) then
  11229. begin
  11230. AsmL.Remove(hp5);
  11231. ASmL.InsertBefore(hp5,hp1)
  11232. end;
  11233. Result:=true;
  11234. end;
  11235. {$endif x86_64}
  11236. end;
  11237. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  11238. var
  11239. Value, RegName: string;
  11240. begin
  11241. Result:=false;
  11242. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  11243. begin
  11244. case taicpu(p).oper[0]^.val of
  11245. 0:
  11246. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  11247. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11248. begin
  11249. { change "mov $0,%reg" into "xor %reg,%reg" }
  11250. taicpu(p).opcode := A_XOR;
  11251. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  11252. Result := True;
  11253. {$ifdef x86_64}
  11254. end
  11255. else if (taicpu(p).opsize = S_Q) then
  11256. begin
  11257. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11258. { The actual optimization }
  11259. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11260. taicpu(p).changeopsize(S_L);
  11261. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11262. Result := True;
  11263. end;
  11264. $1..$FFFFFFFF:
  11265. begin
  11266. { Code size reduction by J. Gareth "Kit" Moreton }
  11267. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  11268. case taicpu(p).opsize of
  11269. S_Q:
  11270. begin
  11271. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  11272. Value := debug_tostr(taicpu(p).oper[0]^.val);
  11273. { The actual optimization }
  11274. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11275. taicpu(p).changeopsize(S_L);
  11276. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  11277. Result := True;
  11278. end;
  11279. else
  11280. { Do nothing };
  11281. end;
  11282. {$endif x86_64}
  11283. end;
  11284. -1:
  11285. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  11286. if (cs_opt_size in current_settings.optimizerswitches) and
  11287. (taicpu(p).opsize <> S_B) and
  11288. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11289. begin
  11290. { change "mov $-1,%reg" into "or $-1,%reg" }
  11291. { NOTES:
  11292. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  11293. - This operation creates a false dependency on the register, so only do it when optimising for size
  11294. - 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
  11295. }
  11296. taicpu(p).opcode := A_OR;
  11297. Result := True;
  11298. end;
  11299. else
  11300. { Do nothing };
  11301. end;
  11302. end;
  11303. end;
  11304. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  11305. var
  11306. hp1: tai;
  11307. begin
  11308. { Detect:
  11309. andw x, %ax (0 <= x < $8000)
  11310. ...
  11311. movzwl %ax,%eax
  11312. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11313. }
  11314. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  11315. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11316. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  11317. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11318. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11319. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11320. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11321. begin
  11322. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  11323. taicpu(hp1).opcode := A_CWDE;
  11324. taicpu(hp1).clearop(0);
  11325. taicpu(hp1).clearop(1);
  11326. taicpu(hp1).ops := 0;
  11327. { A change was made, but not with p, so move forward 1 }
  11328. p := tai(p.Next);
  11329. Result := True;
  11330. end;
  11331. end;
  11332. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  11333. begin
  11334. Result := False;
  11335. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  11336. Exit;
  11337. { Convert:
  11338. movswl %ax,%eax -> cwtl
  11339. movslq %eax,%rax -> cdqe
  11340. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  11341. refer to the same opcode and depends only on the assembler's
  11342. current operand-size attribute. [Kit]
  11343. }
  11344. with taicpu(p) do
  11345. case opsize of
  11346. S_WL:
  11347. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  11348. begin
  11349. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  11350. opcode := A_CWDE;
  11351. clearop(0);
  11352. clearop(1);
  11353. ops := 0;
  11354. Result := True;
  11355. end;
  11356. {$ifdef x86_64}
  11357. S_LQ:
  11358. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  11359. begin
  11360. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  11361. opcode := A_CDQE;
  11362. clearop(0);
  11363. clearop(1);
  11364. ops := 0;
  11365. Result := True;
  11366. end;
  11367. {$endif x86_64}
  11368. else
  11369. ;
  11370. end;
  11371. end;
  11372. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  11373. var
  11374. hp1: tai;
  11375. begin
  11376. { Detect:
  11377. shr x, %ax (x > 0)
  11378. ...
  11379. movzwl %ax,%eax
  11380. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  11381. }
  11382. Result := False;
  11383. if MatchOpType(taicpu(p), top_const, top_reg) and
  11384. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  11385. (taicpu(p).oper[0]^.val > 0) and
  11386. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  11387. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  11388. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  11389. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  11390. begin
  11391. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  11392. taicpu(hp1).opcode := A_CWDE;
  11393. taicpu(hp1).clearop(0);
  11394. taicpu(hp1).clearop(1);
  11395. taicpu(hp1).ops := 0;
  11396. { A change was made, but not with p, so move forward 1 }
  11397. p := tai(p.Next);
  11398. Result := True;
  11399. end;
  11400. end;
  11401. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  11402. var
  11403. hp1, hp2: tai;
  11404. Opposite, SecondOpposite: TAsmOp;
  11405. NewCond: TAsmCond;
  11406. begin
  11407. Result := False;
  11408. { Change:
  11409. add/sub 128,(dest)
  11410. To:
  11411. sub/add -128,(dest)
  11412. This generaally takes fewer bytes to encode because -128 can be stored
  11413. in a signed byte, whereas +128 cannot.
  11414. }
  11415. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  11416. begin
  11417. if taicpu(p).opcode = A_ADD then
  11418. Opposite := A_SUB
  11419. else
  11420. Opposite := A_ADD;
  11421. { Be careful if the flags are in use, because the CF flag inverts
  11422. when changing from ADD to SUB and vice versa }
  11423. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11424. GetNextInstruction(p, hp1) then
  11425. begin
  11426. TransferUsedRegs(TmpUsedRegs);
  11427. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  11428. hp2 := hp1;
  11429. { Scan ahead to check if everything's safe }
  11430. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  11431. begin
  11432. if (hp1.typ <> ait_instruction) then
  11433. { Probably unsafe since the flags are still in use }
  11434. Exit;
  11435. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  11436. { Stop searching at an unconditional jump }
  11437. Break;
  11438. if not
  11439. (
  11440. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  11441. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  11442. ) and
  11443. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  11444. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  11445. Exit;
  11446. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11447. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  11448. { Move to the next instruction }
  11449. GetNextInstruction(hp1, hp1);
  11450. end;
  11451. while Assigned(hp2) and (hp2 <> hp1) do
  11452. begin
  11453. NewCond := C_None;
  11454. case taicpu(hp2).condition of
  11455. C_A, C_NBE:
  11456. NewCond := C_BE;
  11457. C_B, C_C, C_NAE:
  11458. NewCond := C_AE;
  11459. C_AE, C_NB, C_NC:
  11460. NewCond := C_B;
  11461. C_BE, C_NA:
  11462. NewCond := C_A;
  11463. else
  11464. { No change needed };
  11465. end;
  11466. if NewCond <> C_None then
  11467. begin
  11468. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  11469. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  11470. taicpu(hp2).condition := NewCond;
  11471. end
  11472. else
  11473. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  11474. begin
  11475. { Because of the flipping of the carry bit, to ensure
  11476. the operation remains equivalent, ADC becomes SBB
  11477. and vice versa, and the constant is not-inverted.
  11478. If multiple ADCs or SBBs appear in a row, each one
  11479. changed causes the carry bit to invert, so they all
  11480. need to be flipped }
  11481. if taicpu(hp2).opcode = A_ADC then
  11482. SecondOpposite := A_SBB
  11483. else
  11484. SecondOpposite := A_ADC;
  11485. if taicpu(hp2).oper[0]^.typ <> top_const then
  11486. { Should have broken out of this optimisation already }
  11487. InternalError(2021112901);
  11488. 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]^) + ' -> ' +
  11489. 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);
  11490. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  11491. taicpu(hp2).opcode := SecondOpposite;
  11492. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  11493. end;
  11494. { Move to the next instruction }
  11495. GetNextInstruction(hp2, hp2);
  11496. end;
  11497. if (hp2 <> hp1) then
  11498. InternalError(2021111501);
  11499. end;
  11500. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  11501. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  11502. taicpu(p).opcode := Opposite;
  11503. taicpu(p).oper[0]^.val := -128;
  11504. { No further optimisations can be made on this instruction, so move
  11505. onto the next one to save time }
  11506. p := tai(p.Next);
  11507. UpdateUsedRegs(p);
  11508. Result := True;
  11509. Exit;
  11510. end;
  11511. { Detect:
  11512. add/sub %reg2,(dest)
  11513. add/sub x, (dest)
  11514. (dest can be a register or a reference)
  11515. Swap the instructions to minimise a pipeline stall. This reverses the
  11516. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  11517. optimisations could be made.
  11518. }
  11519. if (taicpu(p).oper[0]^.typ = top_reg) and
  11520. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  11521. (
  11522. (
  11523. (taicpu(p).oper[1]^.typ = top_reg) and
  11524. { We can try searching further ahead if we're writing to a register }
  11525. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  11526. ) or
  11527. (
  11528. (taicpu(p).oper[1]^.typ = top_ref) and
  11529. GetNextInstruction(p, hp1)
  11530. )
  11531. ) and
  11532. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  11533. (taicpu(hp1).oper[0]^.typ = top_const) and
  11534. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  11535. begin
  11536. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  11537. TransferUsedRegs(TmpUsedRegs);
  11538. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11539. hp2 := p;
  11540. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  11541. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  11542. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  11543. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  11544. begin
  11545. asml.remove(hp1);
  11546. asml.InsertBefore(hp1, p);
  11547. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  11548. Result := True;
  11549. end;
  11550. end;
  11551. end;
  11552. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  11553. begin
  11554. Result:=false;
  11555. { change "cmp $0, %reg" to "test %reg, %reg" }
  11556. if MatchOpType(taicpu(p),top_const,top_reg) and
  11557. (taicpu(p).oper[0]^.val = 0) then
  11558. begin
  11559. taicpu(p).opcode := A_TEST;
  11560. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  11561. Result:=true;
  11562. end;
  11563. end;
  11564. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  11565. var
  11566. IsTestConstX : Boolean;
  11567. hp1,hp2 : tai;
  11568. begin
  11569. Result:=false;
  11570. { removes the line marked with (x) from the sequence
  11571. and/or/xor/add/sub/... $x, %y
  11572. test/or %y, %y | test $-1, %y (x)
  11573. j(n)z _Label
  11574. as the first instruction already adjusts the ZF
  11575. %y operand may also be a reference }
  11576. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  11577. MatchOperand(taicpu(p).oper[0]^,-1);
  11578. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  11579. GetLastInstruction(p, hp1) and
  11580. (tai(hp1).typ = ait_instruction) and
  11581. GetNextInstruction(p,hp2) and
  11582. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  11583. case taicpu(hp1).opcode Of
  11584. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  11585. { These two instructions set the zero flag if the result is zero }
  11586. A_POPCNT, A_LZCNT:
  11587. begin
  11588. if (
  11589. { With POPCNT, an input of zero will set the zero flag
  11590. because the population count of zero is zero }
  11591. (taicpu(hp1).opcode = A_POPCNT) and
  11592. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  11593. (
  11594. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  11595. { Faster than going through the second half of the 'or'
  11596. condition below }
  11597. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  11598. )
  11599. ) or (
  11600. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  11601. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11602. { and in case of carry for A(E)/B(E)/C/NC }
  11603. (
  11604. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  11605. (
  11606. (taicpu(hp1).opcode <> A_ADD) and
  11607. (taicpu(hp1).opcode <> A_SUB) and
  11608. (taicpu(hp1).opcode <> A_LZCNT)
  11609. )
  11610. )
  11611. ) then
  11612. begin
  11613. RemoveCurrentP(p, hp2);
  11614. Result:=true;
  11615. Exit;
  11616. end;
  11617. end;
  11618. A_SHL, A_SAL, A_SHR, A_SAR:
  11619. begin
  11620. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  11621. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  11622. { therefore, it's only safe to do this optimization for }
  11623. { shifts by a (nonzero) constant }
  11624. (taicpu(hp1).oper[0]^.typ = top_const) and
  11625. (taicpu(hp1).oper[0]^.val <> 0) and
  11626. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11627. { and in case of carry for A(E)/B(E)/C/NC }
  11628. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11629. begin
  11630. RemoveCurrentP(p, hp2);
  11631. Result:=true;
  11632. Exit;
  11633. end;
  11634. end;
  11635. A_DEC, A_INC, A_NEG:
  11636. begin
  11637. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  11638. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  11639. { and in case of carry for A(E)/B(E)/C/NC }
  11640. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  11641. begin
  11642. RemoveCurrentP(p, hp2);
  11643. Result:=true;
  11644. Exit;
  11645. end;
  11646. end
  11647. else
  11648. ;
  11649. end; { case }
  11650. { change "test $-1,%reg" into "test %reg,%reg" }
  11651. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  11652. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  11653. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  11654. if MatchInstruction(p, A_OR, []) and
  11655. { Can only match if they're both registers }
  11656. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  11657. begin
  11658. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  11659. taicpu(p).opcode := A_TEST;
  11660. { No need to set Result to True, as we've done all the optimisations we can }
  11661. end;
  11662. end;
  11663. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  11664. var
  11665. hp1,hp3 : tai;
  11666. {$ifndef x86_64}
  11667. hp2 : taicpu;
  11668. {$endif x86_64}
  11669. begin
  11670. Result:=false;
  11671. hp3:=nil;
  11672. {$ifndef x86_64}
  11673. { don't do this on modern CPUs, this really hurts them due to
  11674. broken call/ret pairing }
  11675. if (current_settings.optimizecputype < cpu_Pentium2) and
  11676. not(cs_create_pic in current_settings.moduleswitches) and
  11677. GetNextInstruction(p, hp1) and
  11678. MatchInstruction(hp1,A_JMP,[S_NO]) and
  11679. MatchOpType(taicpu(hp1),top_ref) and
  11680. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  11681. begin
  11682. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  11683. InsertLLItem(p.previous, p, hp2);
  11684. taicpu(p).opcode := A_JMP;
  11685. taicpu(p).is_jmp := true;
  11686. RemoveInstruction(hp1);
  11687. Result:=true;
  11688. end
  11689. else
  11690. {$endif x86_64}
  11691. { replace
  11692. call procname
  11693. ret
  11694. by
  11695. jmp procname
  11696. but do it only on level 4 because it destroys stack back traces
  11697. else if the subroutine is marked as no return, remove the ret
  11698. }
  11699. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  11700. (po_noreturn in current_procinfo.procdef.procoptions)) and
  11701. GetNextInstruction(p, hp1) and
  11702. (MatchInstruction(hp1,A_RET,[S_NO]) or
  11703. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  11704. SetAndTest(hp1,hp3) and
  11705. GetNextInstruction(hp1,hp1) and
  11706. MatchInstruction(hp1,A_RET,[S_NO])
  11707. )
  11708. ) and
  11709. (taicpu(hp1).ops=0) then
  11710. begin
  11711. if (cs_opt_level4 in current_settings.optimizerswitches) and
  11712. { we might destroy stack alignment here if we do not do a call }
  11713. (target_info.stackalign<=sizeof(SizeUInt)) then
  11714. begin
  11715. taicpu(p).opcode := A_JMP;
  11716. taicpu(p).is_jmp := true;
  11717. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  11718. end
  11719. else
  11720. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  11721. RemoveInstruction(hp1);
  11722. if Assigned(hp3) then
  11723. begin
  11724. AsmL.Remove(hp3);
  11725. AsmL.InsertBefore(hp3,p)
  11726. end;
  11727. Result:=true;
  11728. end;
  11729. end;
  11730. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  11731. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  11732. begin
  11733. case OpSize of
  11734. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11735. Result := (Val <= $FF) and (Val >= -128);
  11736. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11737. Result := (Val <= $FFFF) and (Val >= -32768);
  11738. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  11739. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  11740. else
  11741. Result := True;
  11742. end;
  11743. end;
  11744. var
  11745. hp1, hp2 : tai;
  11746. SizeChange: Boolean;
  11747. PreMessage: string;
  11748. begin
  11749. Result := False;
  11750. if (taicpu(p).oper[0]^.typ = top_reg) and
  11751. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11752. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  11753. begin
  11754. { Change (using movzbl %al,%eax as an example):
  11755. movzbl %al, %eax movzbl %al, %eax
  11756. cmpl x, %eax testl %eax,%eax
  11757. To:
  11758. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  11759. movzbl %al, %eax movzbl %al, %eax
  11760. Smaller instruction and minimises pipeline stall as the CPU
  11761. doesn't have to wait for the register to get zero-extended. [Kit]
  11762. Also allow if the smaller of the two registers is being checked,
  11763. as this still removes the false dependency.
  11764. }
  11765. if
  11766. (
  11767. (
  11768. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  11769. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  11770. ) or (
  11771. { If MatchOperand returns True, they must both be registers }
  11772. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  11773. )
  11774. ) and
  11775. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  11776. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  11777. begin
  11778. 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);
  11779. asml.Remove(hp1);
  11780. asml.InsertBefore(hp1, p);
  11781. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  11782. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  11783. begin
  11784. taicpu(hp1).opcode := A_TEST;
  11785. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  11786. end;
  11787. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11788. case taicpu(p).opsize of
  11789. S_BW, S_BL:
  11790. begin
  11791. SizeChange := taicpu(hp1).opsize <> S_B;
  11792. taicpu(hp1).changeopsize(S_B);
  11793. end;
  11794. S_WL:
  11795. begin
  11796. SizeChange := taicpu(hp1).opsize <> S_W;
  11797. taicpu(hp1).changeopsize(S_W);
  11798. end
  11799. else
  11800. InternalError(2020112701);
  11801. end;
  11802. UpdateUsedRegs(tai(p.Next));
  11803. { Check if the register is used aferwards - if not, we can
  11804. remove the movzx instruction completely }
  11805. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  11806. begin
  11807. { Hp1 is a better position than p for debugging purposes }
  11808. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  11809. RemoveCurrentp(p, hp1);
  11810. Result := True;
  11811. end;
  11812. if SizeChange then
  11813. DebugMsg(SPeepholeOptimization + PreMessage +
  11814. 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)
  11815. else
  11816. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  11817. Exit;
  11818. end;
  11819. { Change (using movzwl %ax,%eax as an example):
  11820. movzwl %ax, %eax
  11821. movb %al, (dest) (Register is smaller than read register in movz)
  11822. To:
  11823. movb %al, (dest) (Move one back to avoid a false dependency)
  11824. movzwl %ax, %eax
  11825. }
  11826. if (taicpu(hp1).opcode = A_MOV) and
  11827. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11828. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  11829. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  11830. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  11831. begin
  11832. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  11833. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  11834. asml.Remove(hp1);
  11835. asml.InsertBefore(hp1, p);
  11836. if taicpu(hp1).oper[1]^.typ = top_reg then
  11837. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  11838. { Check if the register is used aferwards - if not, we can
  11839. remove the movzx instruction completely }
  11840. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  11841. begin
  11842. { Hp1 is a better position than p for debugging purposes }
  11843. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  11844. RemoveCurrentp(p, hp1);
  11845. Result := True;
  11846. end;
  11847. Exit;
  11848. end;
  11849. end;
  11850. end;
  11851. {$ifdef x86_64}
  11852. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  11853. var
  11854. PreMessage, RegName: string;
  11855. begin
  11856. { Code size reduction by J. Gareth "Kit" Moreton }
  11857. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  11858. as this removes the REX prefix }
  11859. Result := False;
  11860. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  11861. Exit;
  11862. if taicpu(p).oper[0]^.typ <> top_reg then
  11863. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  11864. InternalError(2018011500);
  11865. case taicpu(p).opsize of
  11866. S_Q:
  11867. begin
  11868. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  11869. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  11870. { The actual optimization }
  11871. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11872. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  11873. taicpu(p).changeopsize(S_L);
  11874. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  11875. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  11876. end;
  11877. else
  11878. ;
  11879. end;
  11880. end;
  11881. {$endif}
  11882. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  11883. var
  11884. XReg: TRegister;
  11885. begin
  11886. Result := False;
  11887. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  11888. Smaller encoding and slightly faster on some platforms (also works for
  11889. ZMM-sized registers) }
  11890. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  11891. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  11892. begin
  11893. XReg := taicpu(p).oper[0]^.reg;
  11894. if (taicpu(p).oper[1]^.reg = XReg) then
  11895. begin
  11896. taicpu(p).changeopsize(S_XMM);
  11897. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  11898. if (cs_opt_size in current_settings.optimizerswitches) then
  11899. begin
  11900. { Change input registers to %xmm0 to reduce size. Note that
  11901. there's a risk of a false dependency doing this, so only
  11902. optimise for size here }
  11903. XReg := NR_XMM0;
  11904. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  11905. end
  11906. else
  11907. begin
  11908. setsubreg(XReg, R_SUBMMX);
  11909. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  11910. end;
  11911. taicpu(p).oper[0]^.reg := XReg;
  11912. taicpu(p).oper[1]^.reg := XReg;
  11913. Result := True;
  11914. end;
  11915. end;
  11916. end;
  11917. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  11918. var
  11919. OperIdx: Integer;
  11920. begin
  11921. for OperIdx := 0 to p.ops - 1 do
  11922. if p.oper[OperIdx]^.typ = top_ref then
  11923. optimize_ref(p.oper[OperIdx]^.ref^, False);
  11924. end;
  11925. end.