aoptx86.pas 677 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767
  1. {
  2. Copyright (c) 1998-2002 by Florian Klaempfl and Jonas Maebe
  3. This unit contains the peephole optimizer.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15. ****************************************************************************
  16. }
  17. unit aoptx86;
  18. {$i fpcdefs.inc}
  19. { $define DEBUG_AOPTCPU}
  20. {$ifdef EXTDEBUG}
  21. {$define DEBUG_AOPTCPU}
  22. {$endif EXTDEBUG}
  23. interface
  24. uses
  25. globtype,cclasses,
  26. cpubase,
  27. aasmtai,aasmcpu,
  28. cgbase,cgutils,
  29. aopt,aoptobj;
  30. type
  31. TOptsToCheck = (
  32. aoc_MovAnd2Mov_3,
  33. aoc_ForceNewIteration
  34. );
  35. TX86AsmOptimizer = class(TAsmOptimizer)
  36. { some optimizations are very expensive to check, so the
  37. pre opt pass can be used to set some flags, depending on the found
  38. instructions if it is worth to check a certain optimization }
  39. OptsToCheck : set of TOptsToCheck;
  40. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  41. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  42. class function RegReadByInstruction(reg : TRegister; hp : tai) : boolean; static;
  43. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  44. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  45. { Identical to GetNextInstructionUsingReg, but returns a value indicating
  46. how many instructions away that Next is from Current is.
  47. 0 = failure, equivalent to False in GetNextInstructionUsingReg }
  48. function GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  49. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  50. potentially allowing further optimisation (although it might need to know if
  51. it crossed a conditional jump. }
  52. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  53. {
  54. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  55. the use of a register by allocs/dealloc, so it can ignore calls.
  56. In the following example, GetNextInstructionUsingReg will return the second movq,
  57. GetNextInstructionUsingRegTrackingUse won't.
  58. movq %rdi,%rax
  59. # Register rdi released
  60. # Register rdi allocated
  61. movq %rax,%rdi
  62. While in this example:
  63. movq %rdi,%rax
  64. call proc
  65. movq %rdi,%rax
  66. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  67. won't.
  68. }
  69. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  70. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  71. private
  72. function SkipSimpleInstructions(var hp1: tai): Boolean;
  73. protected
  74. class function IsMOVZXAcceptable: Boolean; static; inline;
  75. { Attempts to allocate a volatile integer register for use between p and hp,
  76. using AUsedRegs for the current register usage information. Returns NR_NO
  77. if no free register could be found }
  78. function GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  79. { Attempts to allocate a volatile MM register for use between p and hp,
  80. using AUsedRegs for the current register usage information. Returns NR_NO
  81. if no free register could be found }
  82. function GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  83. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  84. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  85. { checks whether reading the value in reg1 depends on the value of reg2. This
  86. is very similar to SuperRegisterEquals, except it takes into account that
  87. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  88. depend on the value in AH). }
  89. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  90. { Replaces all references to AOldReg in a memory reference to ANewReg }
  91. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Replaces all references to AOldReg in an operand to ANewReg }
  93. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  94. { Replaces all references to AOldReg in an instruction to ANewReg,
  95. except where the register is being written }
  96. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  97. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  98. or writes to a global symbol }
  99. class function IsRefSafe(const ref: PReference): Boolean; static;
  100. { Returns true if the given MOV instruction can be safely converted to CMOV }
  101. class function CanBeCMOV(p, cond_p: tai) : boolean; static;
  102. { Like UpdateUsedRegs, but ignores deallocations }
  103. class procedure UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai); static;
  104. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  105. class function IsBTXAcceptable(p : tai) : boolean; static;
  106. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  107. conversion was successful }
  108. function ConvertLEA(const p : taicpu): Boolean;
  109. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  110. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  111. procedure DebugMsg(const s : string; p : tai);inline;
  112. class function IsExitCode(p : tai) : boolean; static;
  113. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  114. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  115. procedure RemoveLastDeallocForFuncRes(p : tai);
  116. function DoArithCombineOpt(var p : tai) : Boolean;
  117. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  118. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  119. function PrePeepholeOptSxx(var p : tai) : boolean;
  120. function PrePeepholeOptIMUL(var p : tai) : boolean;
  121. function PrePeepholeOptAND(var p : tai) : boolean;
  122. function OptPass1Test(var p: tai): boolean;
  123. function OptPass1Add(var p: tai): boolean;
  124. function OptPass1AND(var p : tai) : boolean;
  125. function OptPass1_V_MOVAP(var p : tai) : boolean;
  126. function OptPass1VOP(var p : tai) : boolean;
  127. function OptPass1MOV(var p : tai) : boolean;
  128. function OptPass1Movx(var p : tai) : boolean;
  129. function OptPass1MOVXX(var p : tai) : boolean;
  130. function OptPass1OP(var p : tai) : boolean;
  131. function OptPass1LEA(var p : tai) : boolean;
  132. function OptPass1Sub(var p : tai) : boolean;
  133. function OptPass1SHLSAL(var p : tai) : boolean;
  134. function OptPass1SHR(var p : tai) : boolean;
  135. function OptPass1FSTP(var p : tai) : boolean;
  136. function OptPass1FLD(var p : tai) : boolean;
  137. function OptPass1Cmp(var p : tai) : boolean;
  138. function OptPass1PXor(var p : tai) : boolean;
  139. function OptPass1VPXor(var p: tai): boolean;
  140. function OptPass1Imul(var p : tai) : boolean;
  141. function OptPass1Jcc(var p : tai) : boolean;
  142. function OptPass1SHXX(var p: tai): boolean;
  143. function OptPass1VMOVDQ(var p: tai): Boolean;
  144. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  145. function OptPass2Movx(var p : tai): Boolean;
  146. function OptPass2MOV(var p : tai) : boolean;
  147. function OptPass2Imul(var p : tai) : boolean;
  148. function OptPass2Jmp(var p : tai) : boolean;
  149. function OptPass2Jcc(var p : tai) : boolean;
  150. function OptPass2Lea(var p: tai): Boolean;
  151. function OptPass2SUB(var p: tai): Boolean;
  152. function OptPass2ADD(var p : tai): Boolean;
  153. function OptPass2SETcc(var p : tai) : boolean;
  154. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  155. function PostPeepholeOptMov(var p : tai) : Boolean;
  156. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  157. function PostPeepholeOptXor(var p : tai) : Boolean;
  158. function PostPeepholeOptAnd(var p : tai) : boolean;
  159. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  160. function PostPeepholeOptCmp(var p : tai) : Boolean;
  161. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  162. function PostPeepholeOptCall(var p : tai) : Boolean;
  163. function PostPeepholeOptLea(var p : tai) : Boolean;
  164. function PostPeepholeOptPush(var p: tai): Boolean;
  165. function PostPeepholeOptShr(var p : tai) : boolean;
  166. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  167. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  168. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  169. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  170. function TrySwapMovOp(var p, hp1: tai): Boolean;
  171. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  172. { Processor-dependent reference optimisation }
  173. class procedure OptimizeRefs(var p: taicpu); static;
  174. end;
  175. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  176. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  177. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  178. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  179. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  180. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  181. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  182. {$if max_operands>2}
  183. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  184. {$endif max_operands>2}
  185. function RefsEqual(const r1, r2: treference): boolean;
  186. { Note that Result is set to True if the references COULD overlap but the
  187. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  188. might still overlap because %reg2 could be equal to %reg1-4 }
  189. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  190. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  191. { returns true, if ref is a reference using only the registers passed as base and index
  192. and having an offset }
  193. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  194. implementation
  195. uses
  196. cutils,verbose,
  197. systems,
  198. globals,
  199. cpuinfo,
  200. procinfo,
  201. paramgr,
  202. aasmbase,
  203. aoptbase,aoptutils,
  204. symconst,symsym,
  205. cgx86,
  206. itcpugas;
  207. {$ifdef DEBUG_AOPTCPU}
  208. const
  209. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  210. {$else DEBUG_AOPTCPU}
  211. { Empty strings help the optimizer to remove string concatenations that won't
  212. ever appear to the user on release builds. [Kit] }
  213. const
  214. SPeepholeOptimization = '';
  215. {$endif DEBUG_AOPTCPU}
  216. LIST_STEP_SIZE = 4;
  217. {$ifndef 8086}
  218. MAX_CMOV_INSTRUCTIONS = 4;
  219. MAX_CMOV_REGISTERS = 8;
  220. {$endif 8086}
  221. type
  222. TJumpTrackingItem = class(TLinkedListItem)
  223. private
  224. FSymbol: TAsmSymbol;
  225. FRefs: LongInt;
  226. public
  227. constructor Create(ASymbol: TAsmSymbol);
  228. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  229. property Symbol: TAsmSymbol read FSymbol;
  230. property Refs: LongInt read FRefs;
  231. end;
  232. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  233. begin
  234. inherited Create;
  235. FSymbol := ASymbol;
  236. FRefs := 0;
  237. end;
  238. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  239. begin
  240. Inc(FRefs);
  241. end;
  242. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  243. begin
  244. result :=
  245. (instr.typ = ait_instruction) and
  246. (taicpu(instr).opcode = op) and
  247. ((opsize = []) or (taicpu(instr).opsize in opsize));
  248. end;
  249. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  250. begin
  251. result :=
  252. (instr.typ = ait_instruction) and
  253. ((taicpu(instr).opcode = op1) or
  254. (taicpu(instr).opcode = op2)
  255. ) and
  256. ((opsize = []) or (taicpu(instr).opsize in opsize));
  257. end;
  258. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  259. begin
  260. result :=
  261. (instr.typ = ait_instruction) and
  262. ((taicpu(instr).opcode = op1) or
  263. (taicpu(instr).opcode = op2) or
  264. (taicpu(instr).opcode = op3)
  265. ) and
  266. ((opsize = []) or (taicpu(instr).opsize in opsize));
  267. end;
  268. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  269. const opsize : topsizes) : boolean;
  270. var
  271. op : TAsmOp;
  272. begin
  273. result:=false;
  274. if (instr.typ <> ait_instruction) or
  275. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  276. exit;
  277. for op in ops do
  278. begin
  279. if taicpu(instr).opcode = op then
  280. begin
  281. result:=true;
  282. exit;
  283. end;
  284. end;
  285. end;
  286. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  287. begin
  288. result := (oper.typ = top_reg) and (oper.reg = reg);
  289. end;
  290. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  291. begin
  292. result := (oper.typ = top_const) and (oper.val = a);
  293. end;
  294. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  295. begin
  296. result := oper1.typ = oper2.typ;
  297. if result then
  298. case oper1.typ of
  299. top_const:
  300. Result:=oper1.val = oper2.val;
  301. top_reg:
  302. Result:=oper1.reg = oper2.reg;
  303. top_ref:
  304. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  305. else
  306. internalerror(2013102801);
  307. end
  308. end;
  309. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  310. begin
  311. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  312. if result then
  313. case oper1.typ of
  314. top_const:
  315. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  316. top_reg:
  317. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  318. top_ref:
  319. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  320. else
  321. internalerror(2020052401);
  322. end
  323. end;
  324. function RefsEqual(const r1, r2: treference): boolean;
  325. begin
  326. RefsEqual :=
  327. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  328. (r1.relsymbol = r2.relsymbol) and
  329. (r1.segment = r2.segment) and (r1.base = r2.base) and
  330. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  331. (r1.offset = r2.offset) and
  332. (r1.volatility + r2.volatility = []);
  333. end;
  334. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  335. begin
  336. if (r1.symbol<>r2.symbol) then
  337. { If the index registers are different, there's a chance one could
  338. be set so it equals the other symbol }
  339. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  340. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  341. (r1.relsymbol = r2.relsymbol) and
  342. (r1.segment = r2.segment) and (r1.base = r2.base) and
  343. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  344. (r1.volatility + r2.volatility = []) then
  345. { In this case, it all depends on the offsets }
  346. Exit(abs(r1.offset - r2.offset) < Range);
  347. { There's a chance things MIGHT overlap, so take no chances }
  348. Result := True;
  349. end;
  350. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  351. begin
  352. Result:=(ref.offset=0) and
  353. (ref.scalefactor in [0,1]) and
  354. (ref.segment=NR_NO) and
  355. (ref.symbol=nil) and
  356. (ref.relsymbol=nil) and
  357. ((base=NR_INVALID) or
  358. (ref.base=base)) and
  359. ((index=NR_INVALID) or
  360. (ref.index=index)) and
  361. (ref.volatility=[]);
  362. end;
  363. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  364. begin
  365. Result:=(ref.scalefactor in [0,1]) and
  366. (ref.segment=NR_NO) and
  367. (ref.symbol=nil) and
  368. (ref.relsymbol=nil) and
  369. ((base=NR_INVALID) or
  370. (ref.base=base)) and
  371. ((index=NR_INVALID) or
  372. (ref.index=index)) and
  373. (ref.volatility=[]);
  374. end;
  375. function InstrReadsFlags(p: tai): boolean;
  376. begin
  377. InstrReadsFlags := true;
  378. case p.typ of
  379. ait_instruction:
  380. if InsProp[taicpu(p).opcode].Ch*
  381. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  382. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  383. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  384. exit;
  385. ait_label:
  386. exit;
  387. else
  388. ;
  389. end;
  390. InstrReadsFlags := false;
  391. end;
  392. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  393. begin
  394. Next:=Current;
  395. repeat
  396. Result:=GetNextInstruction(Next,Next);
  397. until not (Result) or
  398. not(cs_opt_level3 in current_settings.optimizerswitches) or
  399. (Next.typ<>ait_instruction) or
  400. RegInInstruction(reg,Next) or
  401. is_calljmp(taicpu(Next).opcode);
  402. end;
  403. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  404. var
  405. GetNextResult: Boolean;
  406. begin
  407. Result:=0;
  408. Next:=Current;
  409. repeat
  410. GetNextResult := GetNextInstruction(Next,Next);
  411. if GetNextResult then
  412. Inc(Result)
  413. else
  414. { Must return zero upon hitting the end of the linked list without a match }
  415. Result := 0;
  416. until not (GetNextResult) or
  417. not(cs_opt_level3 in current_settings.optimizerswitches) or
  418. (Next.typ<>ait_instruction) or
  419. RegInInstruction(reg,Next) or
  420. is_calljmp(taicpu(Next).opcode);
  421. end;
  422. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  423. procedure TrackJump(Symbol: TAsmSymbol);
  424. var
  425. Search: TJumpTrackingItem;
  426. begin
  427. { See if an entry already exists in our jump tracking list
  428. (faster to search backwards due to the higher chance of
  429. matching destinations) }
  430. Search := TJumpTrackingItem(JumpTracking.Last);
  431. while Assigned(Search) do
  432. begin
  433. if Search.Symbol = Symbol then
  434. begin
  435. { Found it - remove it so it can be pushed to the front }
  436. JumpTracking.Remove(Search);
  437. Break;
  438. end;
  439. Search := TJumpTrackingItem(Search.Previous);
  440. end;
  441. if not Assigned(Search) then
  442. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  443. JumpTracking.Concat(Search);
  444. Search.IncRefs;
  445. end;
  446. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  447. var
  448. Search: TJumpTrackingItem;
  449. begin
  450. Result := False;
  451. { See if this label appears in the tracking list }
  452. Search := TJumpTrackingItem(JumpTracking.Last);
  453. while Assigned(Search) do
  454. begin
  455. if Search.Symbol = Symbol then
  456. begin
  457. { Found it - let's see what we can discover }
  458. if Search.Symbol.getrefs = Search.Refs then
  459. begin
  460. { Success - all the references are accounted for }
  461. JumpTracking.Remove(Search);
  462. Search.Free;
  463. { It is logically impossible for CrossJump to be false here
  464. because we must have run into a conditional jump for
  465. this label at some point }
  466. if not CrossJump then
  467. InternalError(2022041710);
  468. if JumpTracking.First = nil then
  469. { Tracking list is now empty - no more cross jumps }
  470. CrossJump := False;
  471. Result := True;
  472. Exit;
  473. end;
  474. { If the references don't match, it's possible to enter
  475. this label through other means, so drop out }
  476. Exit;
  477. end;
  478. Search := TJumpTrackingItem(Search.Previous);
  479. end;
  480. end;
  481. var
  482. Next_Label: tai;
  483. begin
  484. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  485. Next := Current;
  486. repeat
  487. Result := GetNextInstruction(Next,Next);
  488. if not Result then
  489. Break;
  490. if Next.typ = ait_align then
  491. Result := SkipAligns(Next, Next);
  492. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  493. if is_calljmpuncondret(taicpu(Next).opcode) then
  494. begin
  495. if (taicpu(Next).opcode = A_JMP) and
  496. { Remove dead code now to save time }
  497. RemoveDeadCodeAfterJump(taicpu(Next)) then
  498. { A jump was removed, but not the current instruction, and
  499. Result doesn't necessarily translate into an optimisation
  500. routine's Result, so use the "Force New Iteration" flag so
  501. mark a new pass }
  502. Include(OptsToCheck, aoc_ForceNewIteration);
  503. if not Assigned(JumpTracking) then
  504. begin
  505. { Cross-label optimisations often causes other optimisations
  506. to perform worse because they're not given the chance to
  507. optimise locally. In this case, don't do the cross-label
  508. optimisations yet, but flag them as a potential possibility
  509. for the next iteration of Pass 1 }
  510. if not NotFirstIteration then
  511. Include(OptsToCheck, aoc_ForceNewIteration);
  512. end
  513. else if IsJumpToLabel(taicpu(Next)) and
  514. GetNextInstruction(Next, Next_Label) and
  515. SkipAligns(Next_Label, Next_Label) then
  516. begin
  517. { If we have JMP .lbl, and the label after it has all of its
  518. references tracked, then this is probably an if-else style of
  519. block and we can keep tracking. If the label for this jump
  520. then appears later and is fully tracked, then it's the end
  521. of the if-else blocks and the code paths converge (thus
  522. marking the end of the cross-jump) }
  523. if (Next_Label.typ = ait_label) then
  524. begin
  525. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  526. begin
  527. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  528. Next := Next_Label;
  529. { CrossJump gets set to false by LabelAccountedFor if the
  530. list is completely emptied (as it indicates that all
  531. code paths have converged). We could avoid this nuance
  532. by moving the TrackJump call to before the
  533. LabelAccountedFor call, but this is slower in situations
  534. where LabelAccountedFor would return False due to the
  535. creation of a new object that is not used and destroyed
  536. soon after. }
  537. CrossJump := True;
  538. Continue;
  539. end;
  540. end
  541. else if (Next_Label.typ <> ait_marker) then
  542. { We just did a RemoveDeadCodeAfterJump, so either we find
  543. a label, the end of the procedure or some kind of marker}
  544. InternalError(2022041720);
  545. end;
  546. Result := False;
  547. Exit;
  548. end
  549. else
  550. begin
  551. if not Assigned(JumpTracking) then
  552. begin
  553. { Cross-label optimisations often causes other optimisations
  554. to perform worse because they're not given the chance to
  555. optimise locally. In this case, don't do the cross-label
  556. optimisations yet, but flag them as a potential possibility
  557. for the next iteration of Pass 1 }
  558. if not NotFirstIteration then
  559. Include(OptsToCheck, aoc_ForceNewIteration);
  560. end
  561. else if IsJumpToLabel(taicpu(Next)) then
  562. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  563. else
  564. { Conditional jumps should always be a jump to label }
  565. InternalError(2022041701);
  566. CrossJump := True;
  567. Continue;
  568. end;
  569. if Next.typ = ait_label then
  570. begin
  571. if not Assigned(JumpTracking) then
  572. begin
  573. { Cross-label optimisations often causes other optimisations
  574. to perform worse because they're not given the chance to
  575. optimise locally. In this case, don't do the cross-label
  576. optimisations yet, but flag them as a potential possibility
  577. for the next iteration of Pass 1 }
  578. if not NotFirstIteration then
  579. Include(OptsToCheck, aoc_ForceNewIteration);
  580. end
  581. else if LabelAccountedFor(tai_label(Next).labsym) then
  582. Continue;
  583. { If we reach here, we're at a label that hasn't been seen before
  584. (or JumpTracking was nil) }
  585. Break;
  586. end;
  587. until not Result or
  588. not (cs_opt_level3 in current_settings.optimizerswitches) or
  589. not (Next.typ in [ait_label, ait_instruction]) or
  590. RegInInstruction(reg,Next);
  591. end;
  592. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  593. begin
  594. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  595. begin
  596. Result:=GetNextInstruction(Current,Next);
  597. exit;
  598. end;
  599. Next:=tai(Current.Next);
  600. Result:=false;
  601. while assigned(Next) do
  602. begin
  603. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  604. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  605. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  606. exit
  607. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  608. begin
  609. Result:=true;
  610. exit;
  611. end;
  612. Next:=tai(Next.Next);
  613. end;
  614. end;
  615. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  616. begin
  617. Result:=RegReadByInstruction(reg,hp);
  618. end;
  619. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  620. var
  621. p: taicpu;
  622. opcount: longint;
  623. begin
  624. RegReadByInstruction := false;
  625. if hp.typ <> ait_instruction then
  626. exit;
  627. p := taicpu(hp);
  628. case p.opcode of
  629. A_CALL:
  630. regreadbyinstruction := true;
  631. A_IMUL:
  632. case p.ops of
  633. 1:
  634. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  635. (
  636. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  637. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  638. );
  639. 2,3:
  640. regReadByInstruction :=
  641. reginop(reg,p.oper[0]^) or
  642. reginop(reg,p.oper[1]^);
  643. else
  644. InternalError(2019112801);
  645. end;
  646. A_MUL:
  647. begin
  648. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  649. (
  650. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  651. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  652. );
  653. end;
  654. A_IDIV,A_DIV:
  655. begin
  656. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  657. (
  658. (getregtype(reg)=R_INTREGISTER) and
  659. (
  660. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  661. )
  662. );
  663. end;
  664. else
  665. begin
  666. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  667. begin
  668. RegReadByInstruction := false;
  669. exit;
  670. end;
  671. for opcount := 0 to p.ops-1 do
  672. if (p.oper[opCount]^.typ = top_ref) and
  673. RegInRef(reg,p.oper[opcount]^.ref^) then
  674. begin
  675. RegReadByInstruction := true;
  676. exit
  677. end;
  678. { special handling for SSE MOVSD }
  679. if (p.opcode=A_MOVSD) and (p.ops>0) then
  680. begin
  681. if p.ops<>2 then
  682. internalerror(2017042702);
  683. regReadByInstruction := reginop(reg,p.oper[0]^) or
  684. (
  685. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  686. );
  687. exit;
  688. end;
  689. with insprop[p.opcode] do
  690. begin
  691. case getregtype(reg) of
  692. R_INTREGISTER:
  693. begin
  694. case getsupreg(reg) of
  695. RS_EAX:
  696. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  697. begin
  698. RegReadByInstruction := true;
  699. exit
  700. end;
  701. RS_ECX:
  702. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  703. begin
  704. RegReadByInstruction := true;
  705. exit
  706. end;
  707. RS_EDX:
  708. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  709. begin
  710. RegReadByInstruction := true;
  711. exit
  712. end;
  713. RS_EBX:
  714. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  715. begin
  716. RegReadByInstruction := true;
  717. exit
  718. end;
  719. RS_ESP:
  720. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  721. begin
  722. RegReadByInstruction := true;
  723. exit
  724. end;
  725. RS_EBP:
  726. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  727. begin
  728. RegReadByInstruction := true;
  729. exit
  730. end;
  731. RS_ESI:
  732. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  733. begin
  734. RegReadByInstruction := true;
  735. exit
  736. end;
  737. RS_EDI:
  738. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  739. begin
  740. RegReadByInstruction := true;
  741. exit
  742. end;
  743. end;
  744. end;
  745. R_MMREGISTER:
  746. begin
  747. case getsupreg(reg) of
  748. RS_XMM0:
  749. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  750. begin
  751. RegReadByInstruction := true;
  752. exit
  753. end;
  754. end;
  755. end;
  756. else
  757. ;
  758. end;
  759. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  760. begin
  761. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  762. begin
  763. case p.condition of
  764. C_A,C_NBE, { CF=0 and ZF=0 }
  765. C_BE,C_NA: { CF=1 or ZF=1 }
  766. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  767. C_AE,C_NB,C_NC, { CF=0 }
  768. C_B,C_NAE,C_C: { CF=1 }
  769. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  770. C_NE,C_NZ, { ZF=0 }
  771. C_E,C_Z: { ZF=1 }
  772. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  773. C_G,C_NLE, { ZF=0 and SF=OF }
  774. C_LE,C_NG: { ZF=1 or SF<>OF }
  775. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  776. C_GE,C_NL, { SF=OF }
  777. C_L,C_NGE: { SF<>OF }
  778. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  779. C_NO, { OF=0 }
  780. C_O: { OF=1 }
  781. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  782. C_NP,C_PO, { PF=0 }
  783. C_P,C_PE: { PF=1 }
  784. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  785. C_NS, { SF=0 }
  786. C_S: { SF=1 }
  787. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  788. else
  789. internalerror(2017042701);
  790. end;
  791. if RegReadByInstruction then
  792. exit;
  793. end;
  794. case getsubreg(reg) of
  795. R_SUBW,R_SUBD,R_SUBQ:
  796. RegReadByInstruction :=
  797. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  798. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  799. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  800. R_SUBFLAGCARRY:
  801. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  802. R_SUBFLAGPARITY:
  803. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  804. R_SUBFLAGAUXILIARY:
  805. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  806. R_SUBFLAGZERO:
  807. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  808. R_SUBFLAGSIGN:
  809. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  810. R_SUBFLAGOVERFLOW:
  811. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  812. R_SUBFLAGINTERRUPT:
  813. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  814. R_SUBFLAGDIRECTION:
  815. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  816. else
  817. internalerror(2017042601);
  818. end;
  819. exit;
  820. end;
  821. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  822. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  823. (p.oper[0]^.reg=p.oper[1]^.reg) then
  824. exit;
  825. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  826. begin
  827. RegReadByInstruction := true;
  828. exit
  829. end;
  830. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  831. begin
  832. RegReadByInstruction := true;
  833. exit
  834. end;
  835. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  836. begin
  837. RegReadByInstruction := true;
  838. exit
  839. end;
  840. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  841. begin
  842. RegReadByInstruction := true;
  843. exit
  844. end;
  845. end;
  846. end;
  847. end;
  848. end;
  849. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  850. begin
  851. result:=false;
  852. if p1.typ<>ait_instruction then
  853. exit;
  854. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  855. exit(true);
  856. if (getregtype(reg)=R_INTREGISTER) and
  857. { change information for xmm movsd are not correct }
  858. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  859. begin
  860. case getsupreg(reg) of
  861. { RS_EAX = RS_RAX on x86-64 }
  862. RS_EAX:
  863. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  864. RS_ECX:
  865. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  866. RS_EDX:
  867. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  868. RS_EBX:
  869. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  870. RS_ESP:
  871. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  872. RS_EBP:
  873. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  874. RS_ESI:
  875. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  876. RS_EDI:
  877. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  878. else
  879. ;
  880. end;
  881. if result then
  882. exit;
  883. end
  884. else if getregtype(reg)=R_MMREGISTER then
  885. begin
  886. case getsupreg(reg) of
  887. RS_XMM0:
  888. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  889. else
  890. ;
  891. end;
  892. if result then
  893. exit;
  894. end
  895. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  896. begin
  897. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  898. exit(true);
  899. case getsubreg(reg) of
  900. R_SUBFLAGCARRY:
  901. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  902. R_SUBFLAGPARITY:
  903. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  904. R_SUBFLAGAUXILIARY:
  905. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  906. R_SUBFLAGZERO:
  907. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  908. R_SUBFLAGSIGN:
  909. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  910. R_SUBFLAGOVERFLOW:
  911. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  912. R_SUBFLAGINTERRUPT:
  913. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  914. R_SUBFLAGDIRECTION:
  915. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  916. R_SUBW,R_SUBD,R_SUBQ:
  917. { Everything except the direction bits }
  918. Result:=
  919. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  920. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  921. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  922. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  923. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  924. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  925. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  926. else
  927. ;
  928. end;
  929. if result then
  930. exit;
  931. end
  932. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  933. exit(true);
  934. Result:=inherited RegInInstruction(Reg, p1);
  935. end;
  936. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  937. const
  938. WriteOps: array[0..3] of set of TInsChange =
  939. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  940. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  941. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  942. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  943. var
  944. OperIdx: Integer;
  945. begin
  946. Result := False;
  947. if p1.typ <> ait_instruction then
  948. exit;
  949. with insprop[taicpu(p1).opcode] do
  950. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  951. begin
  952. case getsubreg(reg) of
  953. R_SUBW,R_SUBD,R_SUBQ:
  954. Result :=
  955. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  956. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  957. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  958. R_SUBFLAGCARRY:
  959. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  960. R_SUBFLAGPARITY:
  961. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  962. R_SUBFLAGAUXILIARY:
  963. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  964. R_SUBFLAGZERO:
  965. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  966. R_SUBFLAGSIGN:
  967. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  968. R_SUBFLAGOVERFLOW:
  969. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  970. R_SUBFLAGINTERRUPT:
  971. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  972. R_SUBFLAGDIRECTION:
  973. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  974. else
  975. internalerror(2017042602);
  976. end;
  977. exit;
  978. end;
  979. case taicpu(p1).opcode of
  980. A_CALL:
  981. { We could potentially set Result to False if the register in
  982. question is non-volatile for the subroutine's calling convention,
  983. but this would require detecting the calling convention in use and
  984. also assuming that the routine doesn't contain malformed assembly
  985. language, for example... so it could only be done under -O4 as it
  986. would be considered a side-effect. [Kit] }
  987. Result := True;
  988. A_MOVSD:
  989. { special handling for SSE MOVSD }
  990. if (taicpu(p1).ops>0) then
  991. begin
  992. if taicpu(p1).ops<>2 then
  993. internalerror(2017042703);
  994. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  995. end;
  996. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  997. so fix it here (FK)
  998. }
  999. A_VMOVSS,
  1000. A_VMOVSD:
  1001. begin
  1002. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  1003. exit;
  1004. end;
  1005. A_IMUL:
  1006. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1007. else
  1008. ;
  1009. end;
  1010. if Result then
  1011. exit;
  1012. with insprop[taicpu(p1).opcode] do
  1013. begin
  1014. if getregtype(reg)=R_INTREGISTER then
  1015. begin
  1016. case getsupreg(reg) of
  1017. RS_EAX:
  1018. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1019. begin
  1020. Result := True;
  1021. exit
  1022. end;
  1023. RS_ECX:
  1024. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1025. begin
  1026. Result := True;
  1027. exit
  1028. end;
  1029. RS_EDX:
  1030. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1031. begin
  1032. Result := True;
  1033. exit
  1034. end;
  1035. RS_EBX:
  1036. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1037. begin
  1038. Result := True;
  1039. exit
  1040. end;
  1041. RS_ESP:
  1042. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1043. begin
  1044. Result := True;
  1045. exit
  1046. end;
  1047. RS_EBP:
  1048. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1049. begin
  1050. Result := True;
  1051. exit
  1052. end;
  1053. RS_ESI:
  1054. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1055. begin
  1056. Result := True;
  1057. exit
  1058. end;
  1059. RS_EDI:
  1060. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1061. begin
  1062. Result := True;
  1063. exit
  1064. end;
  1065. end;
  1066. end;
  1067. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1068. if (WriteOps[OperIdx]*Ch<>[]) and
  1069. { The register doesn't get modified inside a reference }
  1070. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1071. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1072. begin
  1073. Result := true;
  1074. exit
  1075. end;
  1076. end;
  1077. end;
  1078. {$ifdef DEBUG_AOPTCPU}
  1079. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1080. begin
  1081. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1082. end;
  1083. function debug_tostr(i: tcgint): string; inline;
  1084. begin
  1085. Result := tostr(i);
  1086. end;
  1087. function debug_hexstr(i: tcgint): string;
  1088. begin
  1089. Result := '0x';
  1090. case i of
  1091. 0..$FF:
  1092. Result := Result + hexstr(i, 2);
  1093. $100..$FFFF:
  1094. Result := Result + hexstr(i, 4);
  1095. $10000..$FFFFFF:
  1096. Result := Result + hexstr(i, 6);
  1097. $1000000..$FFFFFFFF:
  1098. Result := Result + hexstr(i, 8);
  1099. else
  1100. Result := Result + hexstr(i, 16);
  1101. end;
  1102. end;
  1103. function debug_regname(r: TRegister): string; inline;
  1104. begin
  1105. Result := '%' + std_regname(r);
  1106. end;
  1107. { Debug output function - creates a string representation of an operator }
  1108. function debug_operstr(oper: TOper): string;
  1109. begin
  1110. case oper.typ of
  1111. top_const:
  1112. Result := '$' + debug_tostr(oper.val);
  1113. top_reg:
  1114. Result := debug_regname(oper.reg);
  1115. top_ref:
  1116. begin
  1117. if oper.ref^.offset <> 0 then
  1118. Result := debug_tostr(oper.ref^.offset) + '('
  1119. else
  1120. Result := '(';
  1121. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1122. begin
  1123. Result := Result + debug_regname(oper.ref^.base);
  1124. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1125. Result := Result + ',' + debug_regname(oper.ref^.index);
  1126. end
  1127. else
  1128. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1129. Result := Result + debug_regname(oper.ref^.index);
  1130. if (oper.ref^.scalefactor > 1) then
  1131. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1132. else
  1133. Result := Result + ')';
  1134. end;
  1135. else
  1136. Result := '[UNKNOWN]';
  1137. end;
  1138. end;
  1139. function debug_op2str(opcode: tasmop): string; inline;
  1140. begin
  1141. Result := std_op2str[opcode];
  1142. end;
  1143. function debug_opsize2str(opsize: topsize): string; inline;
  1144. begin
  1145. Result := gas_opsize2str[opsize];
  1146. end;
  1147. {$else DEBUG_AOPTCPU}
  1148. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1149. begin
  1150. end;
  1151. function debug_tostr(i: tcgint): string; inline;
  1152. begin
  1153. Result := '';
  1154. end;
  1155. function debug_hexstr(i: tcgint): string; inline;
  1156. begin
  1157. Result := '';
  1158. end;
  1159. function debug_regname(r: TRegister): string; inline;
  1160. begin
  1161. Result := '';
  1162. end;
  1163. function debug_operstr(oper: TOper): string; inline;
  1164. begin
  1165. Result := '';
  1166. end;
  1167. function debug_op2str(opcode: tasmop): string; inline;
  1168. begin
  1169. Result := '';
  1170. end;
  1171. function debug_opsize2str(opsize: topsize): string; inline;
  1172. begin
  1173. Result := '';
  1174. end;
  1175. {$endif DEBUG_AOPTCPU}
  1176. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1177. begin
  1178. {$ifdef x86_64}
  1179. { Always fine on x86-64 }
  1180. Result := True;
  1181. {$else x86_64}
  1182. Result :=
  1183. {$ifdef i8086}
  1184. (current_settings.cputype >= cpu_386) and
  1185. {$endif i8086}
  1186. (
  1187. { Always accept if optimising for size }
  1188. (cs_opt_size in current_settings.optimizerswitches) or
  1189. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1190. (current_settings.optimizecputype >= cpu_Pentium2)
  1191. );
  1192. {$endif x86_64}
  1193. end;
  1194. { Attempts to allocate a volatile integer register for use between p and hp,
  1195. using AUsedRegs for the current register usage information. Returns NR_NO
  1196. if no free register could be found }
  1197. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1198. var
  1199. RegSet: TCPURegisterSet;
  1200. CurrentSuperReg: Integer;
  1201. CurrentReg: TRegister;
  1202. Currentp: tai;
  1203. Breakout: Boolean;
  1204. begin
  1205. Result := NR_NO;
  1206. RegSet :=
  1207. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1208. current_procinfo.saved_regs_int;
  1209. (*
  1210. { Don't use the frame register unless explicitly allowed (fixes i40111) }
  1211. if ([cs_useebp, cs_userbp] * current_settings.optimizerswitches) = [] then
  1212. Exclude(RegSet, RS_FRAME_POINTER_REG);
  1213. *)
  1214. for CurrentSuperReg in RegSet do
  1215. begin
  1216. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1217. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1218. {$if defined(i386) or defined(i8086)}
  1219. { If the target size is 8-bit, make sure we can actually encode it }
  1220. and (
  1221. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1222. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1223. )
  1224. {$endif i386 or i8086}
  1225. then
  1226. begin
  1227. Currentp := p;
  1228. Breakout := False;
  1229. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1230. begin
  1231. case Currentp.typ of
  1232. ait_instruction:
  1233. begin
  1234. if RegInInstruction(CurrentReg, Currentp) then
  1235. begin
  1236. Breakout := True;
  1237. Break;
  1238. end;
  1239. { Cannot allocate across an unconditional jump }
  1240. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1241. Exit;
  1242. end;
  1243. ait_marker:
  1244. { Don't try anything more if a marker is hit }
  1245. Exit;
  1246. ait_regalloc:
  1247. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1248. begin
  1249. Breakout := True;
  1250. Break;
  1251. end;
  1252. else
  1253. ;
  1254. end;
  1255. end;
  1256. if Breakout then
  1257. { Try the next register }
  1258. Continue;
  1259. { We have a free register available }
  1260. Result := CurrentReg;
  1261. if not DontAlloc then
  1262. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1263. Exit;
  1264. end;
  1265. end;
  1266. end;
  1267. { Attempts to allocate a volatile MM register for use between p and hp,
  1268. using AUsedRegs for the current register usage information. Returns NR_NO
  1269. if no free register could be found }
  1270. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai; DontAlloc: Boolean = False): TRegister;
  1271. var
  1272. RegSet: TCPURegisterSet;
  1273. CurrentSuperReg: Integer;
  1274. CurrentReg: TRegister;
  1275. Currentp: tai;
  1276. Breakout: Boolean;
  1277. begin
  1278. Result := NR_NO;
  1279. RegSet :=
  1280. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1281. current_procinfo.saved_regs_mm;
  1282. for CurrentSuperReg in RegSet do
  1283. begin
  1284. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1285. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1286. begin
  1287. Currentp := p;
  1288. Breakout := False;
  1289. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1290. begin
  1291. case Currentp.typ of
  1292. ait_instruction:
  1293. begin
  1294. if RegInInstruction(CurrentReg, Currentp) then
  1295. begin
  1296. Breakout := True;
  1297. Break;
  1298. end;
  1299. { Cannot allocate across an unconditional jump }
  1300. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1301. Exit;
  1302. end;
  1303. ait_marker:
  1304. { Don't try anything more if a marker is hit }
  1305. Exit;
  1306. ait_regalloc:
  1307. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1308. begin
  1309. Breakout := True;
  1310. Break;
  1311. end;
  1312. else
  1313. ;
  1314. end;
  1315. end;
  1316. if Breakout then
  1317. { Try the next register }
  1318. Continue;
  1319. { We have a free register available }
  1320. Result := CurrentReg;
  1321. if not DontAlloc then
  1322. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1323. Exit;
  1324. end;
  1325. end;
  1326. end;
  1327. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1328. begin
  1329. if not SuperRegistersEqual(reg1,reg2) then
  1330. exit(false);
  1331. if getregtype(reg1)<>R_INTREGISTER then
  1332. exit(true); {because SuperRegisterEqual is true}
  1333. case getsubreg(reg1) of
  1334. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1335. higher, it preserves the high bits, so the new value depends on
  1336. reg2's previous value. In other words, it is equivalent to doing:
  1337. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1338. R_SUBL:
  1339. exit(getsubreg(reg2)=R_SUBL);
  1340. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1341. higher, it actually does a:
  1342. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1343. R_SUBH:
  1344. exit(getsubreg(reg2)=R_SUBH);
  1345. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1346. bits of reg2:
  1347. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1348. R_SUBW:
  1349. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1350. { a write to R_SUBD always overwrites every other subregister,
  1351. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1352. R_SUBD,
  1353. R_SUBQ:
  1354. exit(true);
  1355. else
  1356. internalerror(2017042801);
  1357. end;
  1358. end;
  1359. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1360. begin
  1361. if not SuperRegistersEqual(reg1,reg2) then
  1362. exit(false);
  1363. if getregtype(reg1)<>R_INTREGISTER then
  1364. exit(true); {because SuperRegisterEqual is true}
  1365. case getsubreg(reg1) of
  1366. R_SUBL:
  1367. exit(getsubreg(reg2)<>R_SUBH);
  1368. R_SUBH:
  1369. exit(getsubreg(reg2)<>R_SUBL);
  1370. R_SUBW,
  1371. R_SUBD,
  1372. R_SUBQ:
  1373. exit(true);
  1374. else
  1375. internalerror(2017042802);
  1376. end;
  1377. end;
  1378. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1379. var
  1380. hp1 : tai;
  1381. l : TCGInt;
  1382. begin
  1383. result:=false;
  1384. { changes the code sequence
  1385. shr/sar const1, x
  1386. shl const2, x
  1387. to
  1388. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1389. if GetNextInstruction(p, hp1) and
  1390. MatchInstruction(hp1,A_SHL,[]) and
  1391. (taicpu(p).oper[0]^.typ = top_const) and
  1392. (taicpu(hp1).oper[0]^.typ = top_const) and
  1393. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1394. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1395. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1396. begin
  1397. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1398. not(cs_opt_size in current_settings.optimizerswitches) then
  1399. begin
  1400. { shr/sar const1, %reg
  1401. shl const2, %reg
  1402. with const1 > const2 }
  1403. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1404. taicpu(hp1).opcode := A_AND;
  1405. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1406. case taicpu(p).opsize Of
  1407. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1408. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1409. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1410. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1411. else
  1412. Internalerror(2017050703)
  1413. end;
  1414. end
  1415. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1416. not(cs_opt_size in current_settings.optimizerswitches) then
  1417. begin
  1418. { shr/sar const1, %reg
  1419. shl const2, %reg
  1420. with const1 < const2 }
  1421. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1422. taicpu(p).opcode := A_AND;
  1423. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1424. case taicpu(p).opsize Of
  1425. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1426. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1427. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1428. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1429. else
  1430. Internalerror(2017050702)
  1431. end;
  1432. end
  1433. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1434. begin
  1435. { shr/sar const1, %reg
  1436. shl const2, %reg
  1437. with const1 = const2 }
  1438. taicpu(p).opcode := A_AND;
  1439. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1440. case taicpu(p).opsize Of
  1441. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1442. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1443. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1444. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1445. else
  1446. Internalerror(2017050701)
  1447. end;
  1448. RemoveInstruction(hp1);
  1449. end;
  1450. end;
  1451. end;
  1452. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1453. var
  1454. opsize : topsize;
  1455. hp1, hp2 : tai;
  1456. tmpref : treference;
  1457. ShiftValue : Cardinal;
  1458. BaseValue : TCGInt;
  1459. begin
  1460. result:=false;
  1461. opsize:=taicpu(p).opsize;
  1462. { changes certain "imul const, %reg"'s to lea sequences }
  1463. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1464. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1465. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1466. if (taicpu(p).oper[0]^.val = 1) then
  1467. if (taicpu(p).ops = 2) then
  1468. { remove "imul $1, reg" }
  1469. begin
  1470. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1471. Result := RemoveCurrentP(p);
  1472. end
  1473. else
  1474. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1475. begin
  1476. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1477. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1478. asml.InsertAfter(hp1, p);
  1479. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1480. RemoveCurrentP(p, hp1);
  1481. Result := True;
  1482. end
  1483. else if ((taicpu(p).ops <= 2) or
  1484. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1485. not(cs_opt_size in current_settings.optimizerswitches) and
  1486. (not(GetNextInstruction(p, hp1)) or
  1487. not((tai(hp1).typ = ait_instruction) and
  1488. ((taicpu(hp1).opcode=A_Jcc) and
  1489. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1490. begin
  1491. {
  1492. imul X, reg1, reg2 to
  1493. lea (reg1,reg1,Y), reg2
  1494. shl ZZ,reg2
  1495. imul XX, reg1 to
  1496. lea (reg1,reg1,YY), reg1
  1497. shl ZZ,reg2
  1498. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1499. it does not exist as a separate optimization target in FPC though.
  1500. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1501. at most two zeros
  1502. }
  1503. reference_reset(tmpref,1,[]);
  1504. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1505. begin
  1506. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1507. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1508. TmpRef.base := taicpu(p).oper[1]^.reg;
  1509. TmpRef.index := taicpu(p).oper[1]^.reg;
  1510. if not(BaseValue in [3,5,9]) then
  1511. Internalerror(2018110101);
  1512. TmpRef.ScaleFactor := BaseValue-1;
  1513. if (taicpu(p).ops = 2) then
  1514. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1515. else
  1516. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1517. AsmL.InsertAfter(hp1,p);
  1518. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1519. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1520. RemoveCurrentP(p, hp1);
  1521. if ShiftValue>0 then
  1522. begin
  1523. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1524. AsmL.InsertAfter(hp2,hp1);
  1525. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1526. end;
  1527. Result := True;
  1528. end;
  1529. end;
  1530. end;
  1531. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1532. begin
  1533. Result := False;
  1534. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1535. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1536. begin
  1537. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1538. taicpu(p).opcode := A_MOV;
  1539. Result := True;
  1540. end;
  1541. end;
  1542. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1543. var
  1544. p: taicpu absolute hp; { Implicit typecast }
  1545. i: Integer;
  1546. begin
  1547. Result := False;
  1548. if not assigned(hp) or
  1549. (hp.typ <> ait_instruction) then
  1550. Exit;
  1551. Prefetch(insprop[p.opcode]);
  1552. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1553. with insprop[p.opcode] do
  1554. begin
  1555. case getsubreg(reg) of
  1556. R_SUBW,R_SUBD,R_SUBQ:
  1557. Result:=
  1558. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1559. uncommon flags are checked first }
  1560. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1561. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1562. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1563. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1564. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1565. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1566. R_SUBFLAGCARRY:
  1567. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1568. R_SUBFLAGPARITY:
  1569. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1570. R_SUBFLAGAUXILIARY:
  1571. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1572. R_SUBFLAGZERO:
  1573. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1574. R_SUBFLAGSIGN:
  1575. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1576. R_SUBFLAGOVERFLOW:
  1577. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1578. R_SUBFLAGINTERRUPT:
  1579. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1580. R_SUBFLAGDIRECTION:
  1581. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1582. else
  1583. internalerror(2017050501);
  1584. end;
  1585. exit;
  1586. end;
  1587. { Handle special cases first }
  1588. case p.opcode of
  1589. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1590. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1591. begin
  1592. Result :=
  1593. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1594. (p.oper[1]^.typ = top_reg) and
  1595. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1596. (
  1597. (p.oper[0]^.typ = top_const) or
  1598. (
  1599. (p.oper[0]^.typ = top_reg) and
  1600. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1601. ) or (
  1602. (p.oper[0]^.typ = top_ref) and
  1603. not RegInRef(reg,p.oper[0]^.ref^)
  1604. )
  1605. );
  1606. end;
  1607. A_MUL, A_IMUL:
  1608. Result :=
  1609. (
  1610. (p.ops=3) and { IMUL only }
  1611. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1612. (
  1613. (
  1614. (p.oper[1]^.typ=top_reg) and
  1615. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1616. ) or (
  1617. (p.oper[1]^.typ=top_ref) and
  1618. not RegInRef(reg,p.oper[1]^.ref^)
  1619. )
  1620. )
  1621. ) or (
  1622. (
  1623. (p.ops=1) and
  1624. (
  1625. (
  1626. (
  1627. (p.oper[0]^.typ=top_reg) and
  1628. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1629. )
  1630. ) or (
  1631. (p.oper[0]^.typ=top_ref) and
  1632. not RegInRef(reg,p.oper[0]^.ref^)
  1633. )
  1634. ) and (
  1635. (
  1636. (p.opsize=S_B) and
  1637. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1638. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1639. ) or (
  1640. (p.opsize=S_W) and
  1641. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1642. ) or (
  1643. (p.opsize=S_L) and
  1644. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1645. {$ifdef x86_64}
  1646. ) or (
  1647. (p.opsize=S_Q) and
  1648. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1649. {$endif x86_64}
  1650. )
  1651. )
  1652. )
  1653. );
  1654. A_CBW:
  1655. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1656. {$ifndef x86_64}
  1657. A_LDS:
  1658. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1659. A_LES:
  1660. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1661. {$endif not x86_64}
  1662. A_LFS:
  1663. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1664. A_LGS:
  1665. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1666. A_LSS:
  1667. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1668. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1669. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1670. A_LODSB:
  1671. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1672. A_LODSW:
  1673. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1674. {$ifdef x86_64}
  1675. A_LODSQ:
  1676. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1677. {$endif x86_64}
  1678. A_LODSD:
  1679. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1680. A_FSTSW, A_FNSTSW:
  1681. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1682. else
  1683. begin
  1684. with insprop[p.opcode] do
  1685. begin
  1686. if (
  1687. { xor %reg,%reg etc. is classed as a new value }
  1688. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1689. MatchOpType(p, top_reg, top_reg) and
  1690. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1691. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1692. ) then
  1693. begin
  1694. Result := True;
  1695. Exit;
  1696. end;
  1697. { Make sure the entire register is overwritten }
  1698. if (getregtype(reg) = R_INTREGISTER) then
  1699. begin
  1700. if (p.ops > 0) then
  1701. begin
  1702. if RegInOp(reg, p.oper[0]^) then
  1703. begin
  1704. if (p.oper[0]^.typ = top_ref) then
  1705. begin
  1706. if RegInRef(reg, p.oper[0]^.ref^) then
  1707. begin
  1708. Result := False;
  1709. Exit;
  1710. end;
  1711. end
  1712. else if (p.oper[0]^.typ = top_reg) then
  1713. begin
  1714. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1715. begin
  1716. Result := False;
  1717. Exit;
  1718. end
  1719. else if ([Ch_WOp1]*Ch<>[]) then
  1720. begin
  1721. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1722. Result := True
  1723. else
  1724. begin
  1725. Result := False;
  1726. Exit;
  1727. end;
  1728. end;
  1729. end;
  1730. end;
  1731. if (p.ops > 1) then
  1732. begin
  1733. if RegInOp(reg, p.oper[1]^) then
  1734. begin
  1735. if (p.oper[1]^.typ = top_ref) then
  1736. begin
  1737. if RegInRef(reg, p.oper[1]^.ref^) then
  1738. begin
  1739. Result := False;
  1740. Exit;
  1741. end;
  1742. end
  1743. else if (p.oper[1]^.typ = top_reg) then
  1744. begin
  1745. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1746. begin
  1747. Result := False;
  1748. Exit;
  1749. end
  1750. else if ([Ch_WOp2]*Ch<>[]) then
  1751. begin
  1752. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1753. Result := True
  1754. else
  1755. begin
  1756. Result := False;
  1757. Exit;
  1758. end;
  1759. end;
  1760. end;
  1761. end;
  1762. if (p.ops > 2) then
  1763. begin
  1764. if RegInOp(reg, p.oper[2]^) then
  1765. begin
  1766. if (p.oper[2]^.typ = top_ref) then
  1767. begin
  1768. if RegInRef(reg, p.oper[2]^.ref^) then
  1769. begin
  1770. Result := False;
  1771. Exit;
  1772. end;
  1773. end
  1774. else if (p.oper[2]^.typ = top_reg) then
  1775. begin
  1776. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1777. begin
  1778. Result := False;
  1779. Exit;
  1780. end
  1781. else if ([Ch_WOp3]*Ch<>[]) then
  1782. begin
  1783. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1784. Result := True
  1785. else
  1786. begin
  1787. Result := False;
  1788. Exit;
  1789. end;
  1790. end;
  1791. end;
  1792. end;
  1793. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1794. begin
  1795. if (p.oper[3]^.typ = top_ref) then
  1796. begin
  1797. if RegInRef(reg, p.oper[3]^.ref^) then
  1798. begin
  1799. Result := False;
  1800. Exit;
  1801. end;
  1802. end
  1803. else if (p.oper[3]^.typ = top_reg) then
  1804. begin
  1805. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1806. begin
  1807. Result := False;
  1808. Exit;
  1809. end
  1810. else if ([Ch_WOp4]*Ch<>[]) then
  1811. begin
  1812. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1813. Result := True
  1814. else
  1815. begin
  1816. Result := False;
  1817. Exit;
  1818. end;
  1819. end;
  1820. end;
  1821. end;
  1822. end;
  1823. end;
  1824. end;
  1825. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1826. case getsupreg(reg) of
  1827. RS_EAX:
  1828. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1829. begin
  1830. Result := True;
  1831. Exit;
  1832. end;
  1833. RS_ECX:
  1834. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1835. begin
  1836. Result := True;
  1837. Exit;
  1838. end;
  1839. RS_EDX:
  1840. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1841. begin
  1842. Result := True;
  1843. Exit;
  1844. end;
  1845. RS_EBX:
  1846. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1847. begin
  1848. Result := True;
  1849. Exit;
  1850. end;
  1851. RS_ESP:
  1852. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1853. begin
  1854. Result := True;
  1855. Exit;
  1856. end;
  1857. RS_EBP:
  1858. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1859. begin
  1860. Result := True;
  1861. Exit;
  1862. end;
  1863. RS_ESI:
  1864. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1865. begin
  1866. Result := True;
  1867. Exit;
  1868. end;
  1869. RS_EDI:
  1870. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1871. begin
  1872. Result := True;
  1873. Exit;
  1874. end;
  1875. else
  1876. ;
  1877. end;
  1878. end;
  1879. end;
  1880. end;
  1881. end;
  1882. end;
  1883. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1884. var
  1885. hp2,hp3 : tai;
  1886. begin
  1887. { some x86-64 issue a NOP before the real exit code }
  1888. if MatchInstruction(p,A_NOP,[]) then
  1889. GetNextInstruction(p,p);
  1890. result:=assigned(p) and (p.typ=ait_instruction) and
  1891. ((taicpu(p).opcode = A_RET) or
  1892. ((taicpu(p).opcode=A_LEAVE) and
  1893. GetNextInstruction(p,hp2) and
  1894. MatchInstruction(hp2,A_RET,[S_NO])
  1895. ) or
  1896. (((taicpu(p).opcode=A_LEA) and
  1897. MatchOpType(taicpu(p),top_ref,top_reg) and
  1898. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1899. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1900. ) and
  1901. GetNextInstruction(p,hp2) and
  1902. MatchInstruction(hp2,A_RET,[S_NO])
  1903. ) or
  1904. ((((taicpu(p).opcode=A_MOV) and
  1905. MatchOpType(taicpu(p),top_reg,top_reg) and
  1906. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1907. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1908. ((taicpu(p).opcode=A_LEA) and
  1909. MatchOpType(taicpu(p),top_ref,top_reg) and
  1910. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1911. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1912. )
  1913. ) and
  1914. GetNextInstruction(p,hp2) and
  1915. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1916. MatchOpType(taicpu(hp2),top_reg) and
  1917. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1918. GetNextInstruction(hp2,hp3) and
  1919. MatchInstruction(hp3,A_RET,[S_NO])
  1920. )
  1921. );
  1922. end;
  1923. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1924. begin
  1925. isFoldableArithOp := False;
  1926. case hp1.opcode of
  1927. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1928. isFoldableArithOp :=
  1929. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1930. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1931. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1932. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1933. (taicpu(hp1).oper[1]^.reg = reg);
  1934. A_INC,A_DEC,A_NEG,A_NOT:
  1935. isFoldableArithOp :=
  1936. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1937. (taicpu(hp1).oper[0]^.reg = reg);
  1938. else
  1939. ;
  1940. end;
  1941. end;
  1942. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1943. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1944. var
  1945. hp2: tai;
  1946. begin
  1947. hp2 := p;
  1948. repeat
  1949. hp2 := tai(hp2.previous);
  1950. if assigned(hp2) and
  1951. (hp2.typ = ait_regalloc) and
  1952. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1953. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1954. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1955. begin
  1956. RemoveInstruction(hp2);
  1957. break;
  1958. end;
  1959. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1960. end;
  1961. begin
  1962. case current_procinfo.procdef.returndef.typ of
  1963. arraydef,recorddef,pointerdef,
  1964. stringdef,enumdef,procdef,objectdef,errordef,
  1965. filedef,setdef,procvardef,
  1966. classrefdef,forwarddef:
  1967. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1968. orddef:
  1969. if current_procinfo.procdef.returndef.size <> 0 then
  1970. begin
  1971. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1972. { for int64/qword }
  1973. if current_procinfo.procdef.returndef.size = 8 then
  1974. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1975. end;
  1976. else
  1977. ;
  1978. end;
  1979. end;
  1980. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1981. var
  1982. hp1,hp2 : tai;
  1983. begin
  1984. result:=false;
  1985. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1986. begin
  1987. { vmova* reg1,reg1
  1988. =>
  1989. <nop> }
  1990. if taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg then
  1991. begin
  1992. RemoveCurrentP(p);
  1993. result:=true;
  1994. exit;
  1995. end;
  1996. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1997. begin
  1998. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1999. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2000. begin
  2001. { vmova* reg1,reg2
  2002. vmova* reg2,reg3
  2003. dealloc reg2
  2004. =>
  2005. vmova* reg1,reg3 }
  2006. TransferUsedRegs(TmpUsedRegs);
  2007. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2008. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  2009. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2010. begin
  2011. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  2012. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2013. RemoveInstruction(hp1);
  2014. result:=true;
  2015. exit;
  2016. end;
  2017. { special case:
  2018. vmova* reg1,<op>
  2019. vmova* <op>,reg1
  2020. =>
  2021. vmova* reg1,<op> }
  2022. if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  2023. ((taicpu(p).oper[0]^.typ<>top_ref) or
  2024. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  2025. ) then
  2026. begin
  2027. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  2028. RemoveInstruction(hp1);
  2029. result:=true;
  2030. exit;
  2031. end
  2032. end
  2033. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2034. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2035. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2036. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2037. ) and
  2038. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2039. begin
  2040. { vmova* reg1,reg2
  2041. vmovs* reg2,<op>
  2042. dealloc reg2
  2043. =>
  2044. vmovs* reg1,reg3 }
  2045. TransferUsedRegs(TmpUsedRegs);
  2046. UpdateUsedRegsBetween(TmpUsedRegs, p, hp1);
  2047. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2048. begin
  2049. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2050. taicpu(p).opcode:=taicpu(hp1).opcode;
  2051. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2052. RemoveInstruction(hp1);
  2053. result:=true;
  2054. exit;
  2055. end
  2056. end;
  2057. end;
  2058. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2059. begin
  2060. if MatchInstruction(hp1,[A_VFMADDPD,
  2061. A_VFMADD132PD,
  2062. A_VFMADD132PS,
  2063. A_VFMADD132SD,
  2064. A_VFMADD132SS,
  2065. A_VFMADD213PD,
  2066. A_VFMADD213PS,
  2067. A_VFMADD213SD,
  2068. A_VFMADD213SS,
  2069. A_VFMADD231PD,
  2070. A_VFMADD231PS,
  2071. A_VFMADD231SD,
  2072. A_VFMADD231SS,
  2073. A_VFMADDSUB132PD,
  2074. A_VFMADDSUB132PS,
  2075. A_VFMADDSUB213PD,
  2076. A_VFMADDSUB213PS,
  2077. A_VFMADDSUB231PD,
  2078. A_VFMADDSUB231PS,
  2079. A_VFMSUB132PD,
  2080. A_VFMSUB132PS,
  2081. A_VFMSUB132SD,
  2082. A_VFMSUB132SS,
  2083. A_VFMSUB213PD,
  2084. A_VFMSUB213PS,
  2085. A_VFMSUB213SD,
  2086. A_VFMSUB213SS,
  2087. A_VFMSUB231PD,
  2088. A_VFMSUB231PS,
  2089. A_VFMSUB231SD,
  2090. A_VFMSUB231SS,
  2091. A_VFMSUBADD132PD,
  2092. A_VFMSUBADD132PS,
  2093. A_VFMSUBADD213PD,
  2094. A_VFMSUBADD213PS,
  2095. A_VFMSUBADD231PD,
  2096. A_VFMSUBADD231PS,
  2097. A_VFNMADD132PD,
  2098. A_VFNMADD132PS,
  2099. A_VFNMADD132SD,
  2100. A_VFNMADD132SS,
  2101. A_VFNMADD213PD,
  2102. A_VFNMADD213PS,
  2103. A_VFNMADD213SD,
  2104. A_VFNMADD213SS,
  2105. A_VFNMADD231PD,
  2106. A_VFNMADD231PS,
  2107. A_VFNMADD231SD,
  2108. A_VFNMADD231SS,
  2109. A_VFNMSUB132PD,
  2110. A_VFNMSUB132PS,
  2111. A_VFNMSUB132SD,
  2112. A_VFNMSUB132SS,
  2113. A_VFNMSUB213PD,
  2114. A_VFNMSUB213PS,
  2115. A_VFNMSUB213SD,
  2116. A_VFNMSUB213SS,
  2117. A_VFNMSUB231PD,
  2118. A_VFNMSUB231PS,
  2119. A_VFNMSUB231SD,
  2120. A_VFNMSUB231SS],[S_NO]) and
  2121. { we mix single and double opperations here because we assume that the compiler
  2122. generates vmovapd only after double operations and vmovaps only after single operations }
  2123. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^.reg) and
  2124. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[2]^.reg) and
  2125. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2126. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2127. begin
  2128. TransferUsedRegs(TmpUsedRegs);
  2129. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2130. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2131. begin
  2132. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2133. if (cs_opt_level3 in current_settings.optimizerswitches) then
  2134. RemoveCurrentP(p)
  2135. else
  2136. RemoveCurrentP(p, hp1); // hp1 is guaranteed to be the immediate next instruction in this case.
  2137. RemoveInstruction(hp2);
  2138. end;
  2139. end
  2140. else if (hp1.typ = ait_instruction) and
  2141. (((taicpu(p).opcode=A_MOVAPS) and
  2142. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2143. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2144. ((taicpu(p).opcode=A_MOVAPD) and
  2145. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2146. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2147. ) and
  2148. GetNextInstructionUsingReg(hp1, hp2, taicpu(hp1).oper[1]^.reg) and
  2149. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2150. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2151. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2152. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) then
  2153. { change
  2154. movapX reg,reg2
  2155. addsX/subsX/... reg3, reg2
  2156. movapX reg2,reg
  2157. to
  2158. addsX/subsX/... reg3,reg
  2159. }
  2160. begin
  2161. TransferUsedRegs(TmpUsedRegs);
  2162. UpdateUsedRegsBetween(TmpUsedRegs, p, hp2);
  2163. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2164. begin
  2165. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2166. debug_op2str(taicpu(p).opcode)+' '+
  2167. debug_op2str(taicpu(hp1).opcode)+' '+
  2168. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2169. { we cannot eliminate the first move if
  2170. the operations uses the same register for source and dest }
  2171. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2172. { Remember that hp1 is not necessarily the immediate
  2173. next instruction }
  2174. RemoveCurrentP(p);
  2175. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2176. RemoveInstruction(hp2);
  2177. result:=true;
  2178. end;
  2179. end
  2180. else if (hp1.typ = ait_instruction) and
  2181. (((taicpu(p).opcode=A_VMOVAPD) and
  2182. (taicpu(hp1).opcode=A_VCOMISD)) or
  2183. ((taicpu(p).opcode=A_VMOVAPS) and
  2184. ((taicpu(hp1).opcode=A_VCOMISS))
  2185. )
  2186. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2187. { change
  2188. movapX reg,reg1
  2189. vcomisX reg1,reg1
  2190. to
  2191. vcomisX reg,reg
  2192. }
  2193. begin
  2194. TransferUsedRegs(TmpUsedRegs);
  2195. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2196. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2197. begin
  2198. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2199. debug_op2str(taicpu(p).opcode)+' '+
  2200. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2201. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2202. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2203. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2204. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2205. RemoveCurrentP(p);
  2206. result:=true;
  2207. exit;
  2208. end;
  2209. end
  2210. end;
  2211. end;
  2212. end;
  2213. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2214. var
  2215. hp1 : tai;
  2216. begin
  2217. result:=false;
  2218. { replace
  2219. V<Op>X %mreg1,%mreg2,%mreg3
  2220. VMovX %mreg3,%mreg4
  2221. dealloc %mreg3
  2222. by
  2223. V<Op>X %mreg1,%mreg2,%mreg4
  2224. ?
  2225. }
  2226. if GetNextInstruction(p,hp1) and
  2227. { we mix single and double operations here because we assume that the compiler
  2228. generates vmovapd only after double operations and vmovaps only after single operations }
  2229. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2230. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2231. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2232. begin
  2233. TransferUsedRegs(TmpUsedRegs);
  2234. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2235. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2236. begin
  2237. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2238. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2239. RemoveInstruction(hp1);
  2240. result:=true;
  2241. end;
  2242. end;
  2243. end;
  2244. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2245. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2246. begin
  2247. Result := False;
  2248. { For safety reasons, only check for exact register matches }
  2249. { Check base register }
  2250. if (ref.base = AOldReg) then
  2251. begin
  2252. ref.base := ANewReg;
  2253. Result := True;
  2254. end;
  2255. { Check index register }
  2256. if (ref.index = AOldReg) then
  2257. begin
  2258. ref.index := ANewReg;
  2259. Result := True;
  2260. end;
  2261. end;
  2262. { Replaces all references to AOldReg in an operand to ANewReg }
  2263. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2264. var
  2265. OldSupReg, NewSupReg: TSuperRegister;
  2266. OldSubReg, NewSubReg: TSubRegister;
  2267. OldRegType: TRegisterType;
  2268. ThisOper: POper;
  2269. begin
  2270. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2271. Result := False;
  2272. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2273. InternalError(2020011801);
  2274. OldSupReg := getsupreg(AOldReg);
  2275. OldSubReg := getsubreg(AOldReg);
  2276. OldRegType := getregtype(AOldReg);
  2277. NewSupReg := getsupreg(ANewReg);
  2278. NewSubReg := getsubreg(ANewReg);
  2279. if OldRegType <> getregtype(ANewReg) then
  2280. InternalError(2020011802);
  2281. if OldSubReg <> NewSubReg then
  2282. InternalError(2020011803);
  2283. case ThisOper^.typ of
  2284. top_reg:
  2285. if (
  2286. (ThisOper^.reg = AOldReg) or
  2287. (
  2288. (OldRegType = R_INTREGISTER) and
  2289. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2290. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2291. (
  2292. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2293. {$ifndef x86_64}
  2294. and (
  2295. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2296. don't have an 8-bit representation }
  2297. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2298. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2299. )
  2300. {$endif x86_64}
  2301. )
  2302. )
  2303. ) then
  2304. begin
  2305. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2306. Result := True;
  2307. end;
  2308. top_ref:
  2309. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2310. Result := True;
  2311. else
  2312. ;
  2313. end;
  2314. end;
  2315. { Replaces all references to AOldReg in an instruction to ANewReg }
  2316. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2317. const
  2318. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2319. var
  2320. OperIdx: Integer;
  2321. begin
  2322. Result := False;
  2323. for OperIdx := 0 to p.ops - 1 do
  2324. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2325. begin
  2326. { The shift and rotate instructions can only use CL }
  2327. if not (
  2328. (OperIdx = 0) and
  2329. { This second condition just helps to avoid unnecessarily
  2330. calling MatchInstruction for 10 different opcodes }
  2331. (p.oper[0]^.reg = NR_CL) and
  2332. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2333. ) then
  2334. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2335. end
  2336. else if p.oper[OperIdx]^.typ = top_ref then
  2337. { It's okay to replace registers in references that get written to }
  2338. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2339. end;
  2340. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2341. begin
  2342. Result :=
  2343. (ref^.index = NR_NO) and
  2344. (
  2345. {$ifdef x86_64}
  2346. (
  2347. (ref^.base = NR_RIP) and
  2348. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  2349. ) or
  2350. {$endif x86_64}
  2351. (ref^.refaddr = addr_full) or
  2352. (ref^.base = NR_STACK_POINTER_REG) or
  2353. (ref^.base = current_procinfo.framepointer)
  2354. );
  2355. end;
  2356. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2357. var
  2358. l: asizeint;
  2359. begin
  2360. Result := False;
  2361. { Should have been checked previously }
  2362. if p.opcode <> A_LEA then
  2363. InternalError(2020072501);
  2364. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2365. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2366. not(cs_opt_size in current_settings.optimizerswitches) then
  2367. exit;
  2368. with p.oper[0]^.ref^ do
  2369. begin
  2370. if (base <> p.oper[1]^.reg) or
  2371. (index <> NR_NO) or
  2372. assigned(symbol) then
  2373. exit;
  2374. l:=offset;
  2375. if (l=1) and UseIncDec then
  2376. begin
  2377. p.opcode:=A_INC;
  2378. p.loadreg(0,p.oper[1]^.reg);
  2379. p.ops:=1;
  2380. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2381. end
  2382. else if (l=-1) and UseIncDec then
  2383. begin
  2384. p.opcode:=A_DEC;
  2385. p.loadreg(0,p.oper[1]^.reg);
  2386. p.ops:=1;
  2387. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2388. end
  2389. else
  2390. begin
  2391. if (l<0) and (l<>-2147483648) then
  2392. begin
  2393. p.opcode:=A_SUB;
  2394. p.loadConst(0,-l);
  2395. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2396. end
  2397. else
  2398. begin
  2399. p.opcode:=A_ADD;
  2400. p.loadConst(0,l);
  2401. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2402. end;
  2403. end;
  2404. end;
  2405. Result := True;
  2406. end;
  2407. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2408. var
  2409. CurrentReg, ReplaceReg: TRegister;
  2410. begin
  2411. Result := False;
  2412. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2413. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2414. case hp.opcode of
  2415. A_FSTSW, A_FNSTSW,
  2416. A_IN, A_INS, A_OUT, A_OUTS,
  2417. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2418. { These routines have explicit operands, but they are restricted in
  2419. what they can be (e.g. IN and OUT can only read from AL, AX or
  2420. EAX. }
  2421. Exit;
  2422. A_IMUL:
  2423. begin
  2424. { The 1-operand version writes to implicit registers
  2425. The 2-operand version reads from the first operator, and reads
  2426. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2427. the 3-operand version reads from a register that it doesn't write to
  2428. }
  2429. case hp.ops of
  2430. 1:
  2431. if (
  2432. (
  2433. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2434. ) or
  2435. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2436. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2437. begin
  2438. Result := True;
  2439. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2440. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2441. end;
  2442. 2:
  2443. { Only modify the first parameter }
  2444. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2445. begin
  2446. Result := True;
  2447. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2448. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2449. end;
  2450. 3:
  2451. { Only modify the second parameter }
  2452. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2453. begin
  2454. Result := True;
  2455. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2456. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2457. end;
  2458. else
  2459. InternalError(2020012901);
  2460. end;
  2461. end;
  2462. else
  2463. if (hp.ops > 0) and
  2464. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2465. begin
  2466. Result := True;
  2467. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2468. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2469. end;
  2470. end;
  2471. end;
  2472. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2473. var
  2474. hp2: tai;
  2475. p_SourceReg, p_TargetReg: TRegister;
  2476. begin
  2477. Result := False;
  2478. { Backward optimisation. If we have:
  2479. func. %reg1,%reg2
  2480. mov %reg2,%reg3
  2481. (dealloc %reg2)
  2482. Change to:
  2483. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2484. Perform similar optimisations with 1, 3 and 4-operand instructions
  2485. that only have one output.
  2486. }
  2487. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2488. begin
  2489. p_SourceReg := taicpu(p).oper[0]^.reg;
  2490. p_TargetReg := taicpu(p).oper[1]^.reg;
  2491. TransferUsedRegs(TmpUsedRegs);
  2492. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2493. GetLastInstruction(p, hp2) and
  2494. (hp2.typ = ait_instruction) and
  2495. { Have to make sure it's an instruction that only reads from
  2496. the first operands and only writes (not reads or modifies) to
  2497. the last one; in essence, a pure function such as BSR, POPCNT
  2498. or ANDN }
  2499. (
  2500. (
  2501. (taicpu(hp2).ops = 1) and
  2502. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2503. ) or
  2504. (
  2505. (taicpu(hp2).ops = 2) and
  2506. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2507. ) or
  2508. (
  2509. (taicpu(hp2).ops = 3) and
  2510. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2511. ) or
  2512. (
  2513. (taicpu(hp2).ops = 4) and
  2514. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2515. )
  2516. ) and
  2517. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2518. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2519. begin
  2520. case taicpu(hp2).opcode of
  2521. A_FSTSW, A_FNSTSW,
  2522. A_IN, A_INS, A_OUT, A_OUTS,
  2523. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2524. { These routines have explicit operands, but they are restricted in
  2525. what they can be (e.g. IN and OUT can only read from AL, AX or
  2526. EAX. }
  2527. ;
  2528. else
  2529. begin
  2530. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2531. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2532. if not RegInInstruction(p_TargetReg, hp2) then
  2533. begin
  2534. { Since we're allocating from an earlier point, we
  2535. need to remove the register from the tracking }
  2536. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2537. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2538. end;
  2539. RemoveCurrentp(p, hp1);
  2540. { If the Func was another MOV instruction, we might get
  2541. "mov %reg,%reg" that doesn't get removed in Pass 2
  2542. otherwise, so deal with it here (also do something
  2543. similar with lea (%reg),%reg}
  2544. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2545. begin
  2546. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2547. if p = hp2 then
  2548. RemoveCurrentp(p)
  2549. else
  2550. RemoveInstruction(hp2);
  2551. end;
  2552. Result := True;
  2553. Exit;
  2554. end;
  2555. end;
  2556. end;
  2557. end;
  2558. end;
  2559. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2560. var
  2561. hp1, hp2, hp3: tai;
  2562. DoOptimisation, TempBool: Boolean;
  2563. {$ifdef x86_64}
  2564. NewConst: TCGInt;
  2565. {$endif x86_64}
  2566. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2567. begin
  2568. if taicpu(hp1).opcode = signed_movop then
  2569. begin
  2570. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2571. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2572. end
  2573. else
  2574. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2575. end;
  2576. function TryConstMerge(var p1, p2: tai): Boolean;
  2577. var
  2578. ThisRef: TReference;
  2579. begin
  2580. Result := False;
  2581. ThisRef := taicpu(p2).oper[1]^.ref^;
  2582. { Only permit writes to the stack, since we can guarantee alignment with that }
  2583. if (ThisRef.index = NR_NO) and
  2584. (
  2585. (ThisRef.base = NR_STACK_POINTER_REG) or
  2586. (ThisRef.base = current_procinfo.framepointer)
  2587. ) then
  2588. begin
  2589. case taicpu(p).opsize of
  2590. S_B:
  2591. begin
  2592. { Word writes must be on a 2-byte boundary }
  2593. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2594. begin
  2595. { Reduce offset of second reference to see if it is sequential with the first }
  2596. Dec(ThisRef.offset, 1);
  2597. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2598. begin
  2599. { Make sure the constants aren't represented as a
  2600. negative number, as these won't merge properly }
  2601. taicpu(p1).opsize := S_W;
  2602. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2603. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2604. RemoveInstruction(p2);
  2605. Result := True;
  2606. end;
  2607. end;
  2608. end;
  2609. S_W:
  2610. begin
  2611. { Longword writes must be on a 4-byte boundary }
  2612. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2613. begin
  2614. { Reduce offset of second reference to see if it is sequential with the first }
  2615. Dec(ThisRef.offset, 2);
  2616. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2617. begin
  2618. { Make sure the constants aren't represented as a
  2619. negative number, as these won't merge properly }
  2620. taicpu(p1).opsize := S_L;
  2621. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2622. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2623. RemoveInstruction(p2);
  2624. Result := True;
  2625. end;
  2626. end;
  2627. end;
  2628. {$ifdef x86_64}
  2629. S_L:
  2630. begin
  2631. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2632. see if the constants can be encoded this way. }
  2633. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2634. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2635. { Quadword writes must be on an 8-byte boundary }
  2636. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2637. begin
  2638. { Reduce offset of second reference to see if it is sequential with the first }
  2639. Dec(ThisRef.offset, 4);
  2640. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2641. begin
  2642. { Make sure the constants aren't represented as a
  2643. negative number, as these won't merge properly }
  2644. taicpu(p1).opsize := S_Q;
  2645. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2646. taicpu(p1).oper[0]^.val := NewConst;
  2647. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2648. RemoveInstruction(p2);
  2649. Result := True;
  2650. end;
  2651. end;
  2652. end;
  2653. {$endif x86_64}
  2654. else
  2655. ;
  2656. end;
  2657. end;
  2658. end;
  2659. var
  2660. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2661. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2662. NewSize: topsize; NewOffset: asizeint;
  2663. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2664. SourceRef, TargetRef: TReference;
  2665. MovAligned, MovUnaligned: TAsmOp;
  2666. ThisRef: TReference;
  2667. JumpTracking: TLinkedList;
  2668. begin
  2669. Result:=false;
  2670. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2671. { remove mov reg1,reg1? }
  2672. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2673. then
  2674. begin
  2675. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2676. { take care of the register (de)allocs following p }
  2677. RemoveCurrentP(p, hp1);
  2678. Result:=true;
  2679. exit;
  2680. end;
  2681. { All the next optimisations require a next instruction }
  2682. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2683. Exit;
  2684. { Prevent compiler warnings }
  2685. p_TargetReg := NR_NO;
  2686. if taicpu(p).oper[1]^.typ = top_reg then
  2687. begin
  2688. { Saves on a large number of dereferences }
  2689. p_TargetReg := taicpu(p).oper[1]^.reg;
  2690. { Look for:
  2691. mov %reg1,%reg2
  2692. ??? %reg2,r/m
  2693. Change to:
  2694. mov %reg1,%reg2
  2695. ??? %reg1,r/m
  2696. }
  2697. if taicpu(p).oper[0]^.typ = top_reg then
  2698. begin
  2699. if RegReadByInstruction(p_TargetReg, hp1) and
  2700. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2701. begin
  2702. { A change has occurred, just not in p }
  2703. Result := True;
  2704. TransferUsedRegs(TmpUsedRegs);
  2705. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2706. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2707. { Just in case something didn't get modified (e.g. an
  2708. implicit register) }
  2709. not RegReadByInstruction(p_TargetReg, hp1) then
  2710. begin
  2711. { We can remove the original MOV }
  2712. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2713. RemoveCurrentp(p, hp1);
  2714. { UsedRegs got updated by RemoveCurrentp }
  2715. Result := True;
  2716. Exit;
  2717. end;
  2718. { If we know a MOV instruction has become a null operation, we might as well
  2719. get rid of it now to save time. }
  2720. if (taicpu(hp1).opcode = A_MOV) and
  2721. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2722. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2723. { Just being a register is enough to confirm it's a null operation }
  2724. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2725. begin
  2726. Result := True;
  2727. { Speed-up to reduce a pipeline stall... if we had something like...
  2728. movl %eax,%edx
  2729. movw %dx,%ax
  2730. ... the second instruction would change to movw %ax,%ax, but
  2731. given that it is now %ax that's active rather than %eax,
  2732. penalties might occur due to a partial register write, so instead,
  2733. change it to a MOVZX instruction when optimising for speed.
  2734. }
  2735. if not (cs_opt_size in current_settings.optimizerswitches) and
  2736. IsMOVZXAcceptable and
  2737. (taicpu(hp1).opsize < taicpu(p).opsize)
  2738. {$ifdef x86_64}
  2739. { operations already implicitly set the upper 64 bits to zero }
  2740. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2741. {$endif x86_64}
  2742. then
  2743. begin
  2744. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2745. case taicpu(p).opsize of
  2746. S_W:
  2747. if taicpu(hp1).opsize = S_B then
  2748. taicpu(hp1).opsize := S_BL
  2749. else
  2750. InternalError(2020012911);
  2751. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2752. case taicpu(hp1).opsize of
  2753. S_B:
  2754. taicpu(hp1).opsize := S_BL;
  2755. S_W:
  2756. taicpu(hp1).opsize := S_WL;
  2757. else
  2758. InternalError(2020012912);
  2759. end;
  2760. else
  2761. InternalError(2020012910);
  2762. end;
  2763. taicpu(hp1).opcode := A_MOVZX;
  2764. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2765. end
  2766. else
  2767. begin
  2768. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2769. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2770. RemoveInstruction(hp1);
  2771. { The instruction after what was hp1 is now the immediate next instruction,
  2772. so we can continue to make optimisations if it's present }
  2773. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2774. Exit;
  2775. hp1 := hp2;
  2776. end;
  2777. end;
  2778. end;
  2779. end;
  2780. end;
  2781. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2782. overwrites the original destination register. e.g.
  2783. movl ###,%reg2d
  2784. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2785. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2786. }
  2787. if (taicpu(p).oper[1]^.typ = top_reg) and
  2788. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2789. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2790. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2791. begin
  2792. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2793. begin
  2794. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2795. case taicpu(p).oper[0]^.typ of
  2796. top_const:
  2797. { We have something like:
  2798. movb $x, %regb
  2799. movzbl %regb,%regd
  2800. Change to:
  2801. movl $x, %regd
  2802. }
  2803. begin
  2804. case taicpu(hp1).opsize of
  2805. S_BW:
  2806. begin
  2807. convert_mov_value(A_MOVSX, $FF);
  2808. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2809. taicpu(p).opsize := S_W;
  2810. end;
  2811. S_BL:
  2812. begin
  2813. convert_mov_value(A_MOVSX, $FF);
  2814. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2815. taicpu(p).opsize := S_L;
  2816. end;
  2817. S_WL:
  2818. begin
  2819. convert_mov_value(A_MOVSX, $FFFF);
  2820. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2821. taicpu(p).opsize := S_L;
  2822. end;
  2823. {$ifdef x86_64}
  2824. S_BQ:
  2825. begin
  2826. convert_mov_value(A_MOVSX, $FF);
  2827. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2828. taicpu(p).opsize := S_Q;
  2829. end;
  2830. S_WQ:
  2831. begin
  2832. convert_mov_value(A_MOVSX, $FFFF);
  2833. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2834. taicpu(p).opsize := S_Q;
  2835. end;
  2836. S_LQ:
  2837. begin
  2838. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2839. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2840. taicpu(p).opsize := S_Q;
  2841. end;
  2842. {$endif x86_64}
  2843. else
  2844. { If hp1 was a MOV instruction, it should have been
  2845. optimised already }
  2846. InternalError(2020021001);
  2847. end;
  2848. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2849. RemoveInstruction(hp1);
  2850. Result := True;
  2851. Exit;
  2852. end;
  2853. top_ref:
  2854. begin
  2855. { We have something like:
  2856. movb mem, %regb
  2857. movzbl %regb,%regd
  2858. Change to:
  2859. movzbl mem, %regd
  2860. }
  2861. ThisRef := taicpu(p).oper[0]^.ref^;
  2862. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2863. begin
  2864. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2865. taicpu(hp1).loadref(0, ThisRef);
  2866. { Make sure any registers in the references are properly tracked }
  2867. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2868. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2869. if (ThisRef.index <> NR_NO) then
  2870. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2871. RemoveCurrentP(p, hp1);
  2872. Result := True;
  2873. Exit;
  2874. end;
  2875. end;
  2876. else
  2877. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2878. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2879. Exit;
  2880. end;
  2881. end
  2882. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2883. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2884. optimised }
  2885. else
  2886. begin
  2887. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2888. RemoveCurrentP(p, hp1);
  2889. Result := True;
  2890. Exit;
  2891. end;
  2892. end;
  2893. if (taicpu(hp1).opcode = A_AND) and
  2894. (taicpu(p).oper[1]^.typ = top_reg) and
  2895. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2896. begin
  2897. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2898. begin
  2899. case taicpu(p).opsize of
  2900. S_L:
  2901. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2902. begin
  2903. { Optimize out:
  2904. mov x, %reg
  2905. and ffffffffh, %reg
  2906. }
  2907. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2908. RemoveInstruction(hp1);
  2909. Result:=true;
  2910. exit;
  2911. end;
  2912. S_Q: { TODO: Confirm if this is even possible }
  2913. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2914. begin
  2915. { Optimize out:
  2916. mov x, %reg
  2917. and ffffffffffffffffh, %reg
  2918. }
  2919. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2920. RemoveInstruction(hp1);
  2921. Result:=true;
  2922. exit;
  2923. end;
  2924. else
  2925. ;
  2926. end;
  2927. if (
  2928. (taicpu(p).oper[0]^.typ=top_reg) or
  2929. (
  2930. (taicpu(p).oper[0]^.typ=top_ref) and
  2931. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2932. )
  2933. ) and
  2934. GetNextInstruction(hp1,hp2) and
  2935. MatchInstruction(hp2,A_TEST,[]) and
  2936. (
  2937. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2938. (
  2939. { If the register being tested is smaller than the one
  2940. that received a bitwise AND, permit it if the constant
  2941. fits into the smaller size }
  2942. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2943. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2944. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2945. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2946. (
  2947. (
  2948. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2949. (taicpu(hp1).oper[0]^.val <= $FF)
  2950. ) or
  2951. (
  2952. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  2953. (taicpu(hp1).oper[0]^.val <= $FFFF)
  2954. {$ifdef x86_64}
  2955. ) or
  2956. (
  2957. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  2958. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  2959. {$endif x86_64}
  2960. )
  2961. )
  2962. )
  2963. ) and
  2964. (
  2965. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2966. MatchOperand(taicpu(hp2).oper[0]^,-1)
  2967. ) and
  2968. GetNextInstruction(hp2,hp3) and
  2969. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2970. (taicpu(hp3).condition in [C_E,C_NE]) then
  2971. begin
  2972. TransferUsedRegs(TmpUsedRegs);
  2973. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2974. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2975. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2976. begin
  2977. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2978. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2979. taicpu(hp1).opcode:=A_TEST;
  2980. { Shrink the TEST instruction down to the smallest possible size }
  2981. case taicpu(hp1).oper[0]^.val of
  2982. 0..255:
  2983. if (taicpu(hp1).opsize <> S_B)
  2984. {$ifndef x86_64}
  2985. and (
  2986. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  2987. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  2988. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  2989. )
  2990. {$endif x86_64}
  2991. then
  2992. begin
  2993. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2994. { Only print debug message if the TEST instruction
  2995. is a different size before and after }
  2996. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  2997. taicpu(hp1).opsize := S_B;
  2998. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2999. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  3000. end;
  3001. 256..65535:
  3002. if (taicpu(hp1).opsize <> S_W) then
  3003. begin
  3004. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3005. { Only print debug message if the TEST instruction
  3006. is a different size before and after }
  3007. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  3008. taicpu(hp1).opsize := S_W;
  3009. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3010. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  3011. end;
  3012. {$ifdef x86_64}
  3013. 65536..$7FFFFFFF:
  3014. if (taicpu(hp1).opsize <> S_L) then
  3015. begin
  3016. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  3017. { Only print debug message if the TEST instruction
  3018. is a different size before and after }
  3019. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  3020. taicpu(hp1).opsize := S_L;
  3021. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  3022. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3023. end;
  3024. {$endif x86_64}
  3025. else
  3026. ;
  3027. end;
  3028. RemoveInstruction(hp2);
  3029. RemoveCurrentP(p, hp1);
  3030. Result:=true;
  3031. exit;
  3032. end;
  3033. end;
  3034. end
  3035. else if IsMOVZXAcceptable and
  3036. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3037. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3038. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3039. then
  3040. begin
  3041. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3042. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3043. case taicpu(p).opsize of
  3044. S_B:
  3045. if (taicpu(hp1).oper[0]^.val = $ff) then
  3046. begin
  3047. { Convert:
  3048. movb x, %regl movb x, %regl
  3049. andw ffh, %regw andl ffh, %regd
  3050. To:
  3051. movzbw x, %regd movzbl x, %regd
  3052. (Identical registers, just different sizes)
  3053. }
  3054. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3055. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3056. case taicpu(hp1).opsize of
  3057. S_W: NewSize := S_BW;
  3058. S_L: NewSize := S_BL;
  3059. {$ifdef x86_64}
  3060. S_Q: NewSize := S_BQ;
  3061. {$endif x86_64}
  3062. else
  3063. InternalError(2018011510);
  3064. end;
  3065. end
  3066. else
  3067. NewSize := S_NO;
  3068. S_W:
  3069. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3070. begin
  3071. { Convert:
  3072. movw x, %regw
  3073. andl ffffh, %regd
  3074. To:
  3075. movzwl x, %regd
  3076. (Identical registers, just different sizes)
  3077. }
  3078. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3079. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3080. case taicpu(hp1).opsize of
  3081. S_L: NewSize := S_WL;
  3082. {$ifdef x86_64}
  3083. S_Q: NewSize := S_WQ;
  3084. {$endif x86_64}
  3085. else
  3086. InternalError(2018011511);
  3087. end;
  3088. end
  3089. else
  3090. NewSize := S_NO;
  3091. else
  3092. NewSize := S_NO;
  3093. end;
  3094. if NewSize <> S_NO then
  3095. begin
  3096. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3097. { The actual optimization }
  3098. taicpu(p).opcode := A_MOVZX;
  3099. taicpu(p).changeopsize(NewSize);
  3100. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3101. { Safeguard if "and" is followed by a conditional command }
  3102. TransferUsedRegs(TmpUsedRegs);
  3103. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3104. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3105. begin
  3106. { At this point, the "and" command is effectively equivalent to
  3107. "test %reg,%reg". This will be handled separately by the
  3108. Peephole Optimizer. [Kit] }
  3109. DebugMsg(SPeepholeOptimization + PreMessage +
  3110. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3111. end
  3112. else
  3113. begin
  3114. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3115. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3116. RemoveInstruction(hp1);
  3117. end;
  3118. Result := True;
  3119. Exit;
  3120. end;
  3121. end;
  3122. end;
  3123. if (taicpu(hp1).opcode = A_OR) and
  3124. (taicpu(p).oper[1]^.typ = top_reg) and
  3125. MatchOperand(taicpu(p).oper[0]^, 0) and
  3126. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3127. begin
  3128. { mov 0, %reg
  3129. or ###,%reg
  3130. Change to (only if the flags are not used):
  3131. mov ###,%reg
  3132. }
  3133. TransferUsedRegs(TmpUsedRegs);
  3134. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3135. DoOptimisation := True;
  3136. { Even if the flags are used, we might be able to do the optimisation
  3137. if the conditions are predictable }
  3138. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3139. begin
  3140. { Only perform if ### = %reg (the same register) or equal to 0,
  3141. so %reg is guaranteed to still have a value of zero }
  3142. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3143. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3144. begin
  3145. hp2 := hp1;
  3146. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3147. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3148. GetNextInstruction(hp2, hp3) do
  3149. begin
  3150. { Don't continue modifying if the flags state is getting changed }
  3151. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3152. Break;
  3153. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3154. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3155. begin
  3156. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3157. begin
  3158. { Condition is always true }
  3159. case taicpu(hp3).opcode of
  3160. A_Jcc:
  3161. begin
  3162. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3163. { Check for jump shortcuts before we destroy the condition }
  3164. DoJumpOptimizations(hp3, TempBool);
  3165. MakeUnconditional(taicpu(hp3));
  3166. Result := True;
  3167. end;
  3168. A_CMOVcc:
  3169. begin
  3170. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3171. taicpu(hp3).opcode := A_MOV;
  3172. taicpu(hp3).condition := C_None;
  3173. Result := True;
  3174. end;
  3175. A_SETcc:
  3176. begin
  3177. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3178. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3179. taicpu(hp3).opcode := A_MOV;
  3180. taicpu(hp3).ops := 2;
  3181. taicpu(hp3).condition := C_None;
  3182. taicpu(hp3).opsize := S_B;
  3183. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3184. taicpu(hp3).loadconst(0, 1);
  3185. Result := True;
  3186. end;
  3187. else
  3188. InternalError(2021090701);
  3189. end;
  3190. end
  3191. 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
  3192. begin
  3193. { Condition is always false }
  3194. case taicpu(hp3).opcode of
  3195. A_Jcc:
  3196. begin
  3197. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3198. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3199. RemoveInstruction(hp3);
  3200. Result := True;
  3201. { Since hp3 was deleted, hp2 must not be updated }
  3202. Continue;
  3203. end;
  3204. A_CMOVcc:
  3205. begin
  3206. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3207. RemoveInstruction(hp3);
  3208. Result := True;
  3209. { Since hp3 was deleted, hp2 must not be updated }
  3210. Continue;
  3211. end;
  3212. A_SETcc:
  3213. begin
  3214. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3215. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3216. taicpu(hp3).opcode := A_MOV;
  3217. taicpu(hp3).ops := 2;
  3218. taicpu(hp3).condition := C_None;
  3219. taicpu(hp3).opsize := S_B;
  3220. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3221. taicpu(hp3).loadconst(0, 0);
  3222. Result := True;
  3223. end;
  3224. else
  3225. InternalError(2021090702);
  3226. end;
  3227. end
  3228. else
  3229. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3230. DoOptimisation := False;
  3231. end;
  3232. hp2 := hp3;
  3233. end;
  3234. { Flags are still in use - don't optimise }
  3235. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3236. DoOptimisation := False;
  3237. end
  3238. else
  3239. DoOptimisation := False;
  3240. end;
  3241. if DoOptimisation then
  3242. begin
  3243. {$ifdef x86_64}
  3244. { OR only supports 32-bit sign-extended constants for 64-bit
  3245. instructions, so compensate for this if the constant is
  3246. encoded as a value greater than or equal to 2^31 }
  3247. if (taicpu(hp1).opsize = S_Q) and
  3248. (taicpu(hp1).oper[0]^.typ = top_const) and
  3249. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3250. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3251. {$endif x86_64}
  3252. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3253. taicpu(hp1).opcode := A_MOV;
  3254. RemoveCurrentP(p, hp1);
  3255. Result := True;
  3256. Exit;
  3257. end;
  3258. end;
  3259. { Next instruction is also a MOV ? }
  3260. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3261. begin
  3262. if MatchOpType(taicpu(p), top_const, top_ref) and
  3263. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3264. TryConstMerge(p, hp1) then
  3265. begin
  3266. Result := True;
  3267. { In case we have four byte writes in a row, check for 2 more
  3268. right now so we don't have to wait for another iteration of
  3269. pass 1
  3270. }
  3271. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3272. case taicpu(p).opsize of
  3273. S_W:
  3274. begin
  3275. if GetNextInstruction(p, hp1) and
  3276. MatchInstruction(hp1, A_MOV, [S_B]) and
  3277. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3278. GetNextInstruction(hp1, hp2) and
  3279. MatchInstruction(hp2, A_MOV, [S_B]) and
  3280. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3281. { Try to merge the two bytes }
  3282. TryConstMerge(hp1, hp2) then
  3283. { Now try to merge the two words (hp2 will get deleted) }
  3284. TryConstMerge(p, hp1);
  3285. end;
  3286. S_L:
  3287. begin
  3288. { Though this only really benefits x86_64 and not i386, it
  3289. gets a potential optimisation done faster and hence
  3290. reduces the number of times OptPass1MOV is entered }
  3291. if GetNextInstruction(p, hp1) and
  3292. MatchInstruction(hp1, A_MOV, [S_W]) and
  3293. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3294. GetNextInstruction(hp1, hp2) and
  3295. MatchInstruction(hp2, A_MOV, [S_W]) and
  3296. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3297. { Try to merge the two words }
  3298. TryConstMerge(hp1, hp2) then
  3299. { This will always fail on i386, so don't bother
  3300. calling it unless we're doing x86_64 }
  3301. {$ifdef x86_64}
  3302. { Now try to merge the two longwords (hp2 will get deleted) }
  3303. TryConstMerge(p, hp1)
  3304. {$endif x86_64}
  3305. ;
  3306. end;
  3307. else
  3308. ;
  3309. end;
  3310. Exit;
  3311. end;
  3312. if (taicpu(p).oper[1]^.typ = top_reg) and
  3313. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3314. begin
  3315. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3316. TransferUsedRegs(TmpUsedRegs);
  3317. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3318. { we have
  3319. mov x, %treg
  3320. mov %treg, y
  3321. }
  3322. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3323. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3324. { we've got
  3325. mov x, %treg
  3326. mov %treg, y
  3327. with %treg is not used after }
  3328. case taicpu(p).oper[0]^.typ Of
  3329. { top_reg is covered by DeepMOVOpt }
  3330. top_const:
  3331. begin
  3332. { change
  3333. mov const, %treg
  3334. mov %treg, y
  3335. to
  3336. mov const, y
  3337. }
  3338. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3339. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3340. begin
  3341. if taicpu(hp1).oper[1]^.typ=top_reg then
  3342. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3343. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3344. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3345. RemoveInstruction(hp1);
  3346. Result:=true;
  3347. Exit;
  3348. end;
  3349. end;
  3350. top_ref:
  3351. case taicpu(hp1).oper[1]^.typ of
  3352. top_reg:
  3353. begin
  3354. { change
  3355. mov mem, %treg
  3356. mov %treg, %reg
  3357. to
  3358. mov mem, %reg"
  3359. }
  3360. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3361. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3362. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3363. RemoveInstruction(hp1);
  3364. Result:=true;
  3365. Exit;
  3366. end;
  3367. top_ref:
  3368. begin
  3369. {$ifdef x86_64}
  3370. { Look for the following to simplify:
  3371. mov x(mem1), %reg
  3372. mov %reg, y(mem2)
  3373. mov x+8(mem1), %reg
  3374. mov %reg, y+8(mem2)
  3375. Change to:
  3376. movdqu x(mem1), %xmmreg
  3377. movdqu %xmmreg, y(mem2)
  3378. ...but only as long as the memory blocks don't overlap
  3379. }
  3380. SourceRef := taicpu(p).oper[0]^.ref^;
  3381. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3382. if (taicpu(p).opsize = S_Q) and
  3383. GetNextInstruction(hp1, hp2) and
  3384. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3385. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3386. begin
  3387. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3388. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3389. Inc(SourceRef.offset, 8);
  3390. if UseAVX then
  3391. begin
  3392. MovAligned := A_VMOVDQA;
  3393. MovUnaligned := A_VMOVDQU;
  3394. end
  3395. else
  3396. begin
  3397. MovAligned := A_MOVDQA;
  3398. MovUnaligned := A_MOVDQU;
  3399. end;
  3400. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3401. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3402. begin
  3403. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3404. Inc(TargetRef.offset, 8);
  3405. if GetNextInstruction(hp2, hp3) and
  3406. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3407. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3408. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3409. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3410. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3411. begin
  3412. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3413. if NewMMReg <> NR_NO then
  3414. begin
  3415. { Remember that the offsets are 8 ahead }
  3416. if ((SourceRef.offset mod 16) = 8) and
  3417. (
  3418. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3419. (SourceRef.base = current_procinfo.framepointer) or
  3420. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3421. ) then
  3422. taicpu(p).opcode := MovAligned
  3423. else
  3424. taicpu(p).opcode := MovUnaligned;
  3425. taicpu(p).opsize := S_XMM;
  3426. taicpu(p).oper[1]^.reg := NewMMReg;
  3427. if ((TargetRef.offset mod 16) = 8) and
  3428. (
  3429. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3430. (TargetRef.base = current_procinfo.framepointer) or
  3431. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3432. ) then
  3433. taicpu(hp1).opcode := MovAligned
  3434. else
  3435. taicpu(hp1).opcode := MovUnaligned;
  3436. taicpu(hp1).opsize := S_XMM;
  3437. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3438. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3439. RemoveInstruction(hp2);
  3440. RemoveInstruction(hp3);
  3441. Result := True;
  3442. Exit;
  3443. end;
  3444. end;
  3445. end
  3446. else
  3447. begin
  3448. { See if the next references are 8 less rather than 8 greater }
  3449. Dec(SourceRef.offset, 16); { -8 the other way }
  3450. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3451. begin
  3452. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3453. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3454. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3455. GetNextInstruction(hp2, hp3) and
  3456. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3457. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3458. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3459. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3460. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3461. begin
  3462. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3463. if NewMMReg <> NR_NO then
  3464. begin
  3465. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3466. if ((SourceRef.offset mod 16) = 0) and
  3467. (
  3468. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3469. (SourceRef.base = current_procinfo.framepointer) or
  3470. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3471. ) then
  3472. taicpu(hp2).opcode := MovAligned
  3473. else
  3474. taicpu(hp2).opcode := MovUnaligned;
  3475. taicpu(hp2).opsize := S_XMM;
  3476. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3477. if ((TargetRef.offset mod 16) = 0) and
  3478. (
  3479. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3480. (TargetRef.base = current_procinfo.framepointer) or
  3481. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3482. ) then
  3483. taicpu(hp3).opcode := MovAligned
  3484. else
  3485. taicpu(hp3).opcode := MovUnaligned;
  3486. taicpu(hp3).opsize := S_XMM;
  3487. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3488. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3489. RemoveInstruction(hp1);
  3490. RemoveCurrentP(p, hp2);
  3491. Result := True;
  3492. Exit;
  3493. end;
  3494. end;
  3495. end;
  3496. end;
  3497. end;
  3498. {$endif x86_64}
  3499. end;
  3500. else
  3501. { The write target should be a reg or a ref }
  3502. InternalError(2021091601);
  3503. end;
  3504. else
  3505. ;
  3506. end
  3507. else
  3508. { %treg is used afterwards, but all eventualities
  3509. other than the first MOV instruction being a constant
  3510. are covered by DeepMOVOpt, so only check for that }
  3511. if (taicpu(p).oper[0]^.typ = top_const) and
  3512. (
  3513. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3514. not (cs_opt_size in current_settings.optimizerswitches) or
  3515. (taicpu(hp1).opsize = S_B)
  3516. ) and
  3517. (
  3518. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3519. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3520. ) then
  3521. begin
  3522. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3523. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3524. end;
  3525. end;
  3526. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3527. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3528. { mov reg1, mem1 or mov mem1, reg1
  3529. mov mem2, reg2 mov reg2, mem2}
  3530. begin
  3531. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3532. { mov reg1, mem1 or mov mem1, reg1
  3533. mov mem2, reg1 mov reg2, mem1}
  3534. begin
  3535. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3536. { Removes the second statement from
  3537. mov reg1, mem1/reg2
  3538. mov mem1/reg2, reg1 }
  3539. begin
  3540. if taicpu(p).oper[0]^.typ=top_reg then
  3541. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3542. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3543. RemoveInstruction(hp1);
  3544. Result:=true;
  3545. exit;
  3546. end
  3547. else
  3548. begin
  3549. TransferUsedRegs(TmpUsedRegs);
  3550. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3551. if (taicpu(p).oper[1]^.typ = top_ref) and
  3552. { mov reg1, mem1
  3553. mov mem2, reg1 }
  3554. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3555. GetNextInstruction(hp1, hp2) and
  3556. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3557. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3558. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3559. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3560. { change to
  3561. mov reg1, mem1 mov reg1, mem1
  3562. mov mem2, reg1 cmp reg1, mem2
  3563. cmp mem1, reg1
  3564. }
  3565. begin
  3566. RemoveInstruction(hp2);
  3567. taicpu(hp1).opcode := A_CMP;
  3568. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3569. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3570. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3571. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3572. end;
  3573. end;
  3574. end
  3575. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3576. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3577. begin
  3578. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3579. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3580. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3581. end
  3582. else
  3583. begin
  3584. TransferUsedRegs(TmpUsedRegs);
  3585. if GetNextInstruction(hp1, hp2) and
  3586. MatchOpType(taicpu(p),top_ref,top_reg) and
  3587. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3588. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3589. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3590. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3591. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3592. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3593. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3594. { mov mem1, %reg1
  3595. mov %reg1, mem2
  3596. mov mem2, reg2
  3597. to:
  3598. mov mem1, reg2
  3599. mov reg2, mem2}
  3600. begin
  3601. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3602. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3603. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3604. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3605. RemoveInstruction(hp2);
  3606. Result := True;
  3607. end
  3608. {$ifdef i386}
  3609. { this is enabled for i386 only, as the rules to create the reg sets below
  3610. are too complicated for x86-64, so this makes this code too error prone
  3611. on x86-64
  3612. }
  3613. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3614. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3615. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3616. { mov mem1, reg1 mov mem1, reg1
  3617. mov reg1, mem2 mov reg1, mem2
  3618. mov mem2, reg2 mov mem2, reg1
  3619. to: to:
  3620. mov mem1, reg1 mov mem1, reg1
  3621. mov mem1, reg2 mov reg1, mem2
  3622. mov reg1, mem2
  3623. or (if mem1 depends on reg1
  3624. and/or if mem2 depends on reg2)
  3625. to:
  3626. mov mem1, reg1
  3627. mov reg1, mem2
  3628. mov reg1, reg2
  3629. }
  3630. begin
  3631. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3632. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3633. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3634. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3635. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3636. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3637. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3638. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3639. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3640. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3641. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3642. end
  3643. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3644. begin
  3645. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3646. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3647. end
  3648. else
  3649. begin
  3650. RemoveInstruction(hp2);
  3651. end
  3652. {$endif i386}
  3653. ;
  3654. end;
  3655. end
  3656. { movl [mem1],reg1
  3657. movl [mem1],reg2
  3658. to
  3659. movl [mem1],reg1
  3660. movl reg1,reg2
  3661. }
  3662. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3663. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3664. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3665. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3666. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3667. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3668. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3669. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3670. begin
  3671. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3672. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3673. end;
  3674. { movl const1,[mem1]
  3675. movl [mem1],reg1
  3676. to
  3677. movl const1,reg1
  3678. movl reg1,[mem1]
  3679. }
  3680. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3681. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3682. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3683. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3684. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3685. begin
  3686. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3687. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3688. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3689. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3690. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3691. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3692. Result:=true;
  3693. exit;
  3694. end;
  3695. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3696. { Change:
  3697. movl %reg1,%reg2
  3698. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3699. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3700. To:
  3701. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3702. movl x(%reg1),%reg1
  3703. movl %reg1,%regX
  3704. }
  3705. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3706. begin
  3707. p_SourceReg := taicpu(p).oper[0]^.reg;
  3708. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3709. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3710. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3711. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3712. GetNextInstruction(hp1, hp2) and
  3713. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3714. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3715. begin
  3716. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3717. if RegInRef(p_TargetReg, SourceRef) and
  3718. { If %reg1 also appears in the second reference, then it will
  3719. not refer to the same memory block as the first reference }
  3720. not RegInRef(p_SourceReg, SourceRef) then
  3721. begin
  3722. { Check to see if the references match if %reg2 is changed to %reg1 }
  3723. if SourceRef.base = p_TargetReg then
  3724. SourceRef.base := p_SourceReg;
  3725. if SourceRef.index = p_TargetReg then
  3726. SourceRef.index := p_SourceReg;
  3727. { RefsEqual also checks to ensure both references are non-volatile }
  3728. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3729. begin
  3730. taicpu(hp2).loadreg(0, p_SourceReg);
  3731. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3732. Result := True;
  3733. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3734. begin
  3735. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3736. RemoveCurrentP(p, hp1);
  3737. Exit;
  3738. end
  3739. else
  3740. begin
  3741. { Check to see if %reg2 is no longer in use }
  3742. TransferUsedRegs(TmpUsedRegs);
  3743. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3744. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3745. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3746. begin
  3747. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3748. RemoveCurrentP(p, hp1);
  3749. Exit;
  3750. end;
  3751. end;
  3752. { If we reach this point, p and hp1 weren't actually modified,
  3753. so we can do a bit more work on this pass }
  3754. end;
  3755. end;
  3756. end;
  3757. end;
  3758. end;
  3759. {$ifdef x86_64}
  3760. { Change:
  3761. movl %reg1l,%reg2l
  3762. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3763. To:
  3764. movl %reg1l,%reg2l
  3765. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  3766. If %reg1 = %reg3, convert to:
  3767. movl %reg1l,%reg2l
  3768. andl %reg1l,%reg1l
  3769. }
  3770. if (taicpu(p).opsize = S_L) and MatchInstruction(hp1,A_MOV,[S_Q]) and
  3771. MatchOpType(taicpu(p), top_reg, top_reg) and
  3772. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  3773. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^.reg) then
  3774. begin
  3775. TransferUsedRegs(TmpUsedRegs);
  3776. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3777. taicpu(hp1).opsize := S_L;
  3778. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  3779. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3780. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  3781. if (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) then
  3782. begin
  3783. { %reg1 = %reg3 }
  3784. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 1)', hp1);
  3785. taicpu(hp1).opcode := A_AND;
  3786. end
  3787. else
  3788. begin
  3789. { %reg1 <> %reg3 }
  3790. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 1)', hp1);
  3791. end;
  3792. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3793. begin
  3794. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8 done', p);
  3795. RemoveCurrentP(p, hp1);
  3796. Result := True;
  3797. Exit;
  3798. end
  3799. else
  3800. begin
  3801. { Initial instruction wasn't actually changed }
  3802. Include(OptsToCheck, aoc_ForceNewIteration);
  3803. { if %reg1 = %reg3, don't do the long-distance lookahead that
  3804. appears below since %reg1 has technically changed }
  3805. if taicpu(hp1).opcode = A_AND then
  3806. Exit;
  3807. end;
  3808. end;
  3809. {$endif x86_64}
  3810. { search further than the next instruction for a mov (as long as it's not a jump) }
  3811. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3812. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3813. (taicpu(p).oper[1]^.typ = top_reg) and
  3814. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3815. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3816. begin
  3817. { we work with hp2 here, so hp1 can be still used later on when
  3818. checking for GetNextInstruction_p }
  3819. hp3 := hp1;
  3820. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3821. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3822. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3823. TransferUsedRegs(TmpUsedRegs);
  3824. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3825. if NotFirstIteration then
  3826. JumpTracking := TLinkedList.Create
  3827. else
  3828. JumpTracking := nil;
  3829. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3830. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3831. (hp2.typ=ait_instruction) do
  3832. begin
  3833. case taicpu(hp2).opcode of
  3834. A_POP:
  3835. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3836. begin
  3837. if not CrossJump and
  3838. not RegUsedBetween(p_TargetReg, p, hp2) then
  3839. begin
  3840. { We can remove the original MOV since the register
  3841. wasn't used between it and its popping from the stack }
  3842. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3843. RemoveCurrentp(p, hp1);
  3844. Result := True;
  3845. JumpTracking.Free;
  3846. Exit;
  3847. end;
  3848. { Can't go any further }
  3849. Break;
  3850. end;
  3851. A_MOV:
  3852. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3853. ((taicpu(p).oper[0]^.typ=top_const) or
  3854. ((taicpu(p).oper[0]^.typ=top_reg) and
  3855. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3856. )
  3857. ) then
  3858. begin
  3859. { we have
  3860. mov x, %treg
  3861. mov %treg, y
  3862. }
  3863. { We don't need to call UpdateUsedRegs for every instruction between
  3864. p and hp2 because the register we're concerned about will not
  3865. become deallocated (otherwise GetNextInstructionUsingReg would
  3866. have stopped at an earlier instruction). [Kit] }
  3867. TempRegUsed :=
  3868. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3869. RegReadByInstruction(p_TargetReg, hp3) or
  3870. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3871. case taicpu(p).oper[0]^.typ Of
  3872. top_reg:
  3873. begin
  3874. { change
  3875. mov %reg, %treg
  3876. mov %treg, y
  3877. to
  3878. mov %reg, y
  3879. }
  3880. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3881. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3882. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3883. begin
  3884. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3885. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3886. if TempRegUsed then
  3887. begin
  3888. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3889. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3890. { Set the start of the next GetNextInstructionUsingRegCond search
  3891. to start at the entry right before hp2 (which is about to be removed) }
  3892. hp3 := tai(hp2.Previous);
  3893. RemoveInstruction(hp2);
  3894. { See if there's more we can optimise }
  3895. Continue;
  3896. end
  3897. else
  3898. begin
  3899. RemoveInstruction(hp2);
  3900. { We can remove the original MOV too }
  3901. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3902. RemoveCurrentP(p, hp1);
  3903. Result:=true;
  3904. JumpTracking.Free;
  3905. Exit;
  3906. end;
  3907. end
  3908. else
  3909. begin
  3910. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3911. taicpu(hp2).loadReg(0, p_SourceReg);
  3912. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3913. { Check to see if the register also appears in the reference }
  3914. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3915. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3916. { Don't remove the first instruction if the temporary register is in use }
  3917. if not TempRegUsed and
  3918. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3919. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3920. begin
  3921. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3922. RemoveCurrentP(p, hp1);
  3923. Result:=true;
  3924. JumpTracking.Free;
  3925. Exit;
  3926. end;
  3927. { No need to set Result to True here. If there's another instruction later
  3928. on that can be optimised, it will be detected when the main Pass 1 loop
  3929. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3930. end;
  3931. end;
  3932. top_const:
  3933. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3934. begin
  3935. { change
  3936. mov const, %treg
  3937. mov %treg, y
  3938. to
  3939. mov const, y
  3940. }
  3941. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3942. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3943. begin
  3944. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3945. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3946. if TempRegUsed then
  3947. begin
  3948. { Don't remove the first instruction if the temporary register is in use }
  3949. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3950. { No need to set Result to True. If there's another instruction later on
  3951. that can be optimised, it will be detected when the main Pass 1 loop
  3952. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3953. end
  3954. else
  3955. begin
  3956. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3957. RemoveCurrentP(p, hp1);
  3958. Result:=true;
  3959. Exit;
  3960. end;
  3961. end;
  3962. end;
  3963. else
  3964. Internalerror(2019103001);
  3965. end;
  3966. end
  3967. else if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3968. begin
  3969. if not CrossJump and
  3970. not RegUsedBetween(p_TargetReg, p, hp2) and
  3971. not RegReadByInstruction(p_TargetReg, hp2) then
  3972. begin
  3973. { Register is not used before it is overwritten }
  3974. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3975. RemoveCurrentp(p, hp1);
  3976. Result := True;
  3977. Exit;
  3978. end;
  3979. if (taicpu(p).oper[0]^.typ = top_const) and
  3980. (taicpu(hp2).oper[0]^.typ = top_const) then
  3981. begin
  3982. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3983. begin
  3984. { Same value - register hasn't changed }
  3985. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3986. RemoveInstruction(hp2);
  3987. Result := True;
  3988. { See if there's more we can optimise }
  3989. Continue;
  3990. end;
  3991. end;
  3992. {$ifdef x86_64}
  3993. end
  3994. { Change:
  3995. movl %reg1l,%reg2l
  3996. ...
  3997. movq %reg2q,%reg3q (%reg1 <> %reg3)
  3998. To:
  3999. movl %reg1l,%reg2l
  4000. ...
  4001. movl %reg1l,%reg3l (Upper 32 bits of %reg3q will be zero)
  4002. If %reg1 = %reg3, convert to:
  4003. movl %reg1l,%reg2l
  4004. ...
  4005. andl %reg1l,%reg1l
  4006. }
  4007. else if (taicpu(p).opsize = S_L) and MatchInstruction(hp2,A_MOV,[S_Q]) and
  4008. (taicpu(p).oper[0]^.typ = top_reg) and
  4009. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4010. SuperRegistersEqual(p_TargetReg, taicpu(hp2).oper[0]^.reg) and
  4011. not RegModifiedBetween(p_TargetReg, p, hp2) then
  4012. begin
  4013. TempRegUsed :=
  4014. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  4015. RegReadByInstruction(p_TargetReg, hp3) or
  4016. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  4017. taicpu(hp2).opsize := S_L;
  4018. taicpu(hp2).loadreg(0, taicpu(p).oper[0]^.reg);
  4019. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4020. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp2, UsedRegs);
  4021. if (taicpu(p).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) then
  4022. begin
  4023. { %reg1 = %reg3 }
  4024. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlAndl 2)', hp2);
  4025. taicpu(hp2).opcode := A_AND;
  4026. end
  4027. else
  4028. begin
  4029. { %reg1 <> %reg3 }
  4030. DebugMsg(SPeepholeOptimization + 'Made 32-to-64-bit zero extension more efficient (MovlMovq2MovlMovl 2)', hp2);
  4031. end;
  4032. if not TempRegUsed then
  4033. begin
  4034. DebugMsg(SPeepholeOptimization + 'Mov2Nop 8a done', p);
  4035. RemoveCurrentP(p, hp1);
  4036. Result := True;
  4037. Exit;
  4038. end
  4039. else
  4040. begin
  4041. { Initial instruction wasn't actually changed }
  4042. Include(OptsToCheck, aoc_ForceNewIteration);
  4043. { if %reg1 = %reg3, don't do the long-distance lookahead that
  4044. appears below since %reg1 has technically changed }
  4045. if taicpu(hp2).opcode = A_AND then
  4046. Break;
  4047. end;
  4048. {$endif x86_64}
  4049. end;
  4050. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  4051. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4052. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  4053. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  4054. begin
  4055. {
  4056. Change from:
  4057. mov ###, %reg
  4058. ...
  4059. movs/z %reg,%reg (Same register, just different sizes)
  4060. To:
  4061. movs/z ###, %reg (Longer version)
  4062. ...
  4063. (remove)
  4064. }
  4065. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  4066. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  4067. { Keep the first instruction as mov if ### is a constant }
  4068. if taicpu(p).oper[0]^.typ = top_const then
  4069. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  4070. else
  4071. begin
  4072. taicpu(p).opcode := taicpu(hp2).opcode;
  4073. taicpu(p).opsize := taicpu(hp2).opsize;
  4074. end;
  4075. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  4076. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  4077. RemoveInstruction(hp2);
  4078. Result := True;
  4079. JumpTracking.Free;
  4080. Exit;
  4081. end;
  4082. else
  4083. { Move down to the if-block below };
  4084. end;
  4085. { Also catches MOV/S/Z instructions that aren't modified }
  4086. if taicpu(p).oper[0]^.typ = top_reg then
  4087. begin
  4088. p_SourceReg := taicpu(p).oper[0]^.reg;
  4089. if
  4090. not RegModifiedByInstruction(p_SourceReg, hp3) and
  4091. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  4092. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  4093. begin
  4094. Result := True;
  4095. { Just in case something didn't get modified (e.g. an
  4096. implicit register). Also, if it does read from this
  4097. register, then there's no longer an advantage to
  4098. changing the register on subsequent instructions.}
  4099. if not RegReadByInstruction(p_TargetReg, hp2) then
  4100. begin
  4101. { If a conditional jump was crossed, do not delete
  4102. the original MOV no matter what }
  4103. if not CrossJump and
  4104. { RegEndOfLife returns True if the register is
  4105. deallocated before the next instruction or has
  4106. been loaded with a new value }
  4107. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  4108. begin
  4109. { We can remove the original MOV }
  4110. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  4111. RemoveCurrentp(p, hp1);
  4112. JumpTracking.Free;
  4113. Result := True;
  4114. Exit;
  4115. end;
  4116. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  4117. begin
  4118. { See if there's more we can optimise }
  4119. hp3 := hp2;
  4120. Continue;
  4121. end;
  4122. end;
  4123. end;
  4124. end;
  4125. { Break out of the while loop under normal circumstances }
  4126. Break;
  4127. end;
  4128. JumpTracking.Free;
  4129. end;
  4130. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  4131. (taicpu(p).oper[1]^.typ = top_reg) and
  4132. (taicpu(p).opsize = S_L) and
  4133. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  4134. (hp2.typ = ait_instruction) and
  4135. (taicpu(hp2).opcode = A_AND) and
  4136. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  4137. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4138. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  4139. ) then
  4140. begin
  4141. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4142. begin
  4143. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4144. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4145. begin
  4146. { Optimize out:
  4147. mov x, %reg
  4148. and ffffffffh, %reg
  4149. }
  4150. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4151. RemoveInstruction(hp2);
  4152. Result:=true;
  4153. exit;
  4154. end;
  4155. end;
  4156. end;
  4157. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4158. x >= RetOffset) as it doesn't do anything (it writes either to a
  4159. parameter or to the temporary storage room for the function
  4160. result)
  4161. }
  4162. if IsExitCode(hp1) and
  4163. (taicpu(p).oper[1]^.typ = top_ref) and
  4164. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4165. (
  4166. (
  4167. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4168. not (
  4169. assigned(current_procinfo.procdef.funcretsym) and
  4170. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4171. )
  4172. ) or
  4173. { Also discard writes to the stack that are below the base pointer,
  4174. as this is temporary storage rather than a function result on the
  4175. stack, say. }
  4176. (
  4177. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4178. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4179. )
  4180. ) then
  4181. begin
  4182. RemoveCurrentp(p, hp1);
  4183. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4184. RemoveLastDeallocForFuncRes(p);
  4185. Result:=true;
  4186. exit;
  4187. end;
  4188. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4189. begin
  4190. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4191. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4192. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4193. begin
  4194. { change
  4195. mov reg1, mem1
  4196. test/cmp x, mem1
  4197. to
  4198. mov reg1, mem1
  4199. test/cmp x, reg1
  4200. }
  4201. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4202. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4203. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4204. Result := True;
  4205. Exit;
  4206. end;
  4207. if DoMovCmpMemOpt(p, hp1, True) then
  4208. begin
  4209. Result := True;
  4210. Exit;
  4211. end;
  4212. end;
  4213. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4214. { If the flags register is in use, don't change the instruction to an
  4215. ADD otherwise this will scramble the flags. [Kit] }
  4216. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4217. begin
  4218. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4219. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4220. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4221. ) or
  4222. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4223. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4224. )
  4225. ) then
  4226. { mov reg1,ref
  4227. lea reg2,[reg1,reg2]
  4228. to
  4229. add reg2,ref}
  4230. begin
  4231. TransferUsedRegs(TmpUsedRegs);
  4232. { reg1 may not be used afterwards }
  4233. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4234. begin
  4235. Taicpu(hp1).opcode:=A_ADD;
  4236. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4237. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4238. RemoveCurrentp(p, hp1);
  4239. result:=true;
  4240. exit;
  4241. end;
  4242. end;
  4243. { If the LEA instruction can be converted into an arithmetic instruction,
  4244. it may be possible to then fold it in the next optimisation, otherwise
  4245. there's nothing more that can be optimised here. }
  4246. if not ConvertLEA(taicpu(hp1)) then
  4247. Exit;
  4248. end;
  4249. if (taicpu(p).oper[1]^.typ = top_reg) and
  4250. (hp1.typ = ait_instruction) and
  4251. GetNextInstruction(hp1, hp2) and
  4252. MatchInstruction(hp2,A_MOV,[]) and
  4253. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4254. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4255. (
  4256. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4257. {$ifdef x86_64}
  4258. or
  4259. (
  4260. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4261. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4262. )
  4263. {$endif x86_64}
  4264. ) then
  4265. begin
  4266. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4267. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4268. { change movsX/movzX reg/ref, reg2
  4269. add/sub/or/... reg3/$const, reg2
  4270. mov reg2 reg/ref
  4271. dealloc reg2
  4272. to
  4273. add/sub/or/... reg3/$const, reg/ref }
  4274. begin
  4275. TransferUsedRegs(TmpUsedRegs);
  4276. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4277. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4278. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4279. begin
  4280. { by example:
  4281. movswl %si,%eax movswl %si,%eax p
  4282. decl %eax addl %edx,%eax hp1
  4283. movw %ax,%si movw %ax,%si hp2
  4284. ->
  4285. movswl %si,%eax movswl %si,%eax p
  4286. decw %eax addw %edx,%eax hp1
  4287. movw %ax,%si movw %ax,%si hp2
  4288. }
  4289. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4290. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4291. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4292. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4293. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4294. {
  4295. ->
  4296. movswl %si,%eax movswl %si,%eax p
  4297. decw %si addw %dx,%si hp1
  4298. movw %ax,%si movw %ax,%si hp2
  4299. }
  4300. case taicpu(hp1).ops of
  4301. 1:
  4302. begin
  4303. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4304. if taicpu(hp1).oper[0]^.typ=top_reg then
  4305. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4306. end;
  4307. 2:
  4308. begin
  4309. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4310. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4311. (taicpu(hp1).opcode<>A_SHL) and
  4312. (taicpu(hp1).opcode<>A_SHR) and
  4313. (taicpu(hp1).opcode<>A_SAR) then
  4314. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4315. end;
  4316. else
  4317. internalerror(2008042701);
  4318. end;
  4319. {
  4320. ->
  4321. decw %si addw %dx,%si p
  4322. }
  4323. RemoveInstruction(hp2);
  4324. RemoveCurrentP(p, hp1);
  4325. Result:=True;
  4326. Exit;
  4327. end;
  4328. end;
  4329. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4330. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4331. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4332. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4333. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4334. )
  4335. {$ifdef i386}
  4336. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4337. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4338. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4339. {$endif i386}
  4340. then
  4341. { change movsX/movzX reg/ref, reg2
  4342. add/sub/or/... regX/$const, reg2
  4343. mov reg2, reg3
  4344. dealloc reg2
  4345. to
  4346. movsX/movzX reg/ref, reg3
  4347. add/sub/or/... reg3/$const, reg3
  4348. }
  4349. begin
  4350. TransferUsedRegs(TmpUsedRegs);
  4351. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4352. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4353. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4354. begin
  4355. { by example:
  4356. movswl %si,%eax movswl %si,%eax p
  4357. decl %eax addl %edx,%eax hp1
  4358. movw %ax,%si movw %ax,%si hp2
  4359. ->
  4360. movswl %si,%eax movswl %si,%eax p
  4361. decw %eax addw %edx,%eax hp1
  4362. movw %ax,%si movw %ax,%si hp2
  4363. }
  4364. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4365. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4366. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4367. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4368. { limit size of constants as well to avoid assembler errors, but
  4369. check opsize to avoid overflow when left shifting the 1 }
  4370. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4371. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4372. {$ifdef x86_64}
  4373. { Be careful of, for example:
  4374. movl %reg1,%reg2
  4375. addl %reg3,%reg2
  4376. movq %reg2,%reg4
  4377. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4378. }
  4379. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4380. begin
  4381. taicpu(hp2).changeopsize(S_L);
  4382. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4383. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4384. end;
  4385. {$endif x86_64}
  4386. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4387. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4388. if taicpu(p).oper[0]^.typ=top_reg then
  4389. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4390. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4391. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4392. {
  4393. ->
  4394. movswl %si,%eax movswl %si,%eax p
  4395. decw %si addw %dx,%si hp1
  4396. movw %ax,%si movw %ax,%si hp2
  4397. }
  4398. case taicpu(hp1).ops of
  4399. 1:
  4400. begin
  4401. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4402. if taicpu(hp1).oper[0]^.typ=top_reg then
  4403. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4404. end;
  4405. 2:
  4406. begin
  4407. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4408. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4409. (taicpu(hp1).opcode<>A_SHL) and
  4410. (taicpu(hp1).opcode<>A_SHR) and
  4411. (taicpu(hp1).opcode<>A_SAR) then
  4412. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4413. end;
  4414. else
  4415. internalerror(2018111801);
  4416. end;
  4417. {
  4418. ->
  4419. decw %si addw %dx,%si p
  4420. }
  4421. RemoveInstruction(hp2);
  4422. end;
  4423. end;
  4424. end;
  4425. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4426. GetNextInstruction(hp1, hp2) and
  4427. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4428. MatchOperand(Taicpu(p).oper[0]^,0) and
  4429. (Taicpu(p).oper[1]^.typ = top_reg) and
  4430. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4431. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4432. { mov reg1,0
  4433. bts reg1,operand1 --> mov reg1,operand2
  4434. or reg1,operand2 bts reg1,operand1}
  4435. begin
  4436. Taicpu(hp2).opcode:=A_MOV;
  4437. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4438. asml.remove(hp1);
  4439. insertllitem(hp2,hp2.next,hp1);
  4440. RemoveCurrentp(p, hp1);
  4441. Result:=true;
  4442. exit;
  4443. end;
  4444. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4445. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4446. GetNextInstruction(hp1, hp2) and
  4447. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4448. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4449. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4450. { change
  4451. mov reg1,reg2
  4452. sub reg3,reg2
  4453. cmp reg3,reg1
  4454. into
  4455. mov reg1,reg2
  4456. sub reg3,reg2
  4457. }
  4458. begin
  4459. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4460. RemoveInstruction(hp2);
  4461. Result:=true;
  4462. exit;
  4463. end;
  4464. {
  4465. mov ref,reg0
  4466. <op> reg0,reg1
  4467. dealloc reg0
  4468. to
  4469. <op> ref,reg1
  4470. }
  4471. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4472. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4473. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4474. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4475. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4476. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4477. begin
  4478. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4479. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4480. RemoveCurrentp(p, hp1);
  4481. Result:=true;
  4482. exit;
  4483. end;
  4484. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4485. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4486. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4487. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4488. begin
  4489. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4490. {$ifdef x86_64}
  4491. { Convert:
  4492. movq x(ref),%reg64
  4493. shrq y,%reg64
  4494. To:
  4495. movl x+4(ref),%reg32
  4496. shrl y-32,%reg32 (Remove if y = 32)
  4497. }
  4498. if (taicpu(p).opsize = S_Q) and
  4499. (taicpu(hp1).opcode = A_SHR) and
  4500. (taicpu(hp1).oper[0]^.val >= 32) then
  4501. begin
  4502. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4503. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4504. { Convert to 32-bit }
  4505. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4506. taicpu(p).opsize := S_L;
  4507. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4508. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4509. if (taicpu(hp1).oper[0]^.val = 32) then
  4510. begin
  4511. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4512. RemoveInstruction(hp1);
  4513. end
  4514. else
  4515. begin
  4516. { This will potentially open up more arithmetic operations since
  4517. the peephole optimizer now has a big hint that only the lower
  4518. 32 bits are currently in use (and opcodes are smaller in size) }
  4519. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4520. taicpu(hp1).opsize := S_L;
  4521. Dec(taicpu(hp1).oper[0]^.val, 32);
  4522. DebugMsg(SPeepholeOptimization + PreMessage +
  4523. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4524. end;
  4525. Result := True;
  4526. Exit;
  4527. end;
  4528. {$endif x86_64}
  4529. { Convert:
  4530. movl x(ref),%reg
  4531. shrl $24,%reg
  4532. To:
  4533. movzbl x+3(ref),%reg
  4534. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4535. Also accept sar instead of shr, but convert to movsx instead of movzx
  4536. }
  4537. if taicpu(hp1).opcode = A_SHR then
  4538. MovUnaligned := A_MOVZX
  4539. else
  4540. MovUnaligned := A_MOVSX;
  4541. NewSize := S_NO;
  4542. NewOffset := 0;
  4543. case taicpu(p).opsize of
  4544. S_B:
  4545. { No valid combinations };
  4546. S_W:
  4547. if (taicpu(hp1).oper[0]^.val = 8) then
  4548. begin
  4549. NewSize := S_BW;
  4550. NewOffset := 1;
  4551. end;
  4552. S_L:
  4553. case taicpu(hp1).oper[0]^.val of
  4554. 16:
  4555. begin
  4556. NewSize := S_WL;
  4557. NewOffset := 2;
  4558. end;
  4559. 24:
  4560. begin
  4561. NewSize := S_BL;
  4562. NewOffset := 3;
  4563. end;
  4564. else
  4565. ;
  4566. end;
  4567. {$ifdef x86_64}
  4568. S_Q:
  4569. case taicpu(hp1).oper[0]^.val of
  4570. 32:
  4571. begin
  4572. if taicpu(hp1).opcode = A_SAR then
  4573. begin
  4574. { 32-bit to 64-bit is a distinct instruction }
  4575. MovUnaligned := A_MOVSXD;
  4576. NewSize := S_LQ;
  4577. NewOffset := 4;
  4578. end
  4579. else
  4580. { Should have been handled by MovShr2Mov above }
  4581. InternalError(2022081811);
  4582. end;
  4583. 48:
  4584. begin
  4585. NewSize := S_WQ;
  4586. NewOffset := 6;
  4587. end;
  4588. 56:
  4589. begin
  4590. NewSize := S_BQ;
  4591. NewOffset := 7;
  4592. end;
  4593. else
  4594. ;
  4595. end;
  4596. {$endif x86_64}
  4597. else
  4598. InternalError(2022081810);
  4599. end;
  4600. if (NewSize <> S_NO) and
  4601. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4602. begin
  4603. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4604. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4605. debug_op2str(MovUnaligned);
  4606. {$ifdef x86_64}
  4607. if MovUnaligned <> A_MOVSXD then
  4608. { Don't add size suffix for MOVSXD }
  4609. {$endif x86_64}
  4610. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4611. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4612. taicpu(p).opcode := MovUnaligned;
  4613. taicpu(p).opsize := NewSize;
  4614. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4615. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4616. RemoveInstruction(hp1);
  4617. Result := True;
  4618. Exit;
  4619. end;
  4620. end;
  4621. { Backward optimisation shared with OptPass2MOV }
  4622. if FuncMov2Func(p, hp1) then
  4623. begin
  4624. Result := True;
  4625. Exit;
  4626. end;
  4627. end;
  4628. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4629. var
  4630. hp1 : tai;
  4631. begin
  4632. Result:=false;
  4633. if taicpu(p).ops <> 2 then
  4634. exit;
  4635. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4636. GetNextInstruction(p,hp1) then
  4637. begin
  4638. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4639. (taicpu(hp1).ops = 2) then
  4640. begin
  4641. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4642. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4643. { movXX reg1, mem1 or movXX mem1, reg1
  4644. movXX mem2, reg2 movXX reg2, mem2}
  4645. begin
  4646. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4647. { movXX reg1, mem1 or movXX mem1, reg1
  4648. movXX mem2, reg1 movXX reg2, mem1}
  4649. begin
  4650. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4651. begin
  4652. { Removes the second statement from
  4653. movXX reg1, mem1/reg2
  4654. movXX mem1/reg2, reg1
  4655. }
  4656. if taicpu(p).oper[0]^.typ=top_reg then
  4657. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4658. { Removes the second statement from
  4659. movXX mem1/reg1, reg2
  4660. movXX reg2, mem1/reg1
  4661. }
  4662. if (taicpu(p).oper[1]^.typ=top_reg) and
  4663. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4664. begin
  4665. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4666. RemoveInstruction(hp1);
  4667. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4668. Result:=true;
  4669. exit;
  4670. end
  4671. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4672. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4673. begin
  4674. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4675. RemoveInstruction(hp1);
  4676. Result:=true;
  4677. exit;
  4678. end;
  4679. end
  4680. end;
  4681. end;
  4682. end;
  4683. end;
  4684. end;
  4685. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4686. var
  4687. hp1 : tai;
  4688. begin
  4689. result:=false;
  4690. { replace
  4691. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4692. MovX %mreg2,%mreg1
  4693. dealloc %mreg2
  4694. by
  4695. <Op>X %mreg2,%mreg1
  4696. ?
  4697. }
  4698. if GetNextInstruction(p,hp1) and
  4699. { we mix single and double opperations here because we assume that the compiler
  4700. generates vmovapd only after double operations and vmovaps only after single operations }
  4701. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4702. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4703. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4704. (taicpu(p).oper[0]^.typ=top_reg) then
  4705. begin
  4706. TransferUsedRegs(TmpUsedRegs);
  4707. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4708. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4709. begin
  4710. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4711. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4712. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4713. RemoveInstruction(hp1);
  4714. result:=true;
  4715. end;
  4716. end;
  4717. end;
  4718. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4719. var
  4720. hp1, p_label, p_dist, hp1_dist: tai;
  4721. JumpLabel, JumpLabel_dist: TAsmLabel;
  4722. FirstValue, SecondValue: TCGInt;
  4723. TempBool: Boolean;
  4724. begin
  4725. Result := False;
  4726. if (taicpu(p).oper[0]^.typ = top_const) and
  4727. (taicpu(p).oper[0]^.val <> -1) then
  4728. begin
  4729. { Convert unsigned maximum constants to -1 to aid optimisation }
  4730. case taicpu(p).opsize of
  4731. S_B:
  4732. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4733. begin
  4734. taicpu(p).oper[0]^.val := -1;
  4735. Result := True;
  4736. Exit;
  4737. end;
  4738. S_W:
  4739. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4740. begin
  4741. taicpu(p).oper[0]^.val := -1;
  4742. Result := True;
  4743. Exit;
  4744. end;
  4745. S_L:
  4746. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4747. begin
  4748. taicpu(p).oper[0]^.val := -1;
  4749. Result := True;
  4750. Exit;
  4751. end;
  4752. {$ifdef x86_64}
  4753. S_Q:
  4754. { Storing anything greater than $7FFFFFFF is not possible so do
  4755. nothing };
  4756. {$endif x86_64}
  4757. else
  4758. InternalError(2021121001);
  4759. end;
  4760. end;
  4761. if GetNextInstruction(p, hp1) and
  4762. TrySwapMovCmp(p, hp1) then
  4763. begin
  4764. Result := True;
  4765. Exit;
  4766. end;
  4767. if MatchInstruction(hp1, A_Jcc, []) then
  4768. begin
  4769. TempBool := True;
  4770. if DoJumpOptimizations(hp1, TempBool) or
  4771. not TempBool then
  4772. begin
  4773. Result := True;
  4774. if Assigned(hp1) then
  4775. begin
  4776. if (hp1.typ in [ait_align]) then
  4777. SkipAligns(hp1, hp1);
  4778. { CollapseZeroDistJump will be set to the label after the
  4779. jump if it optimises, whether or not it's live or dead }
  4780. if (hp1.typ in [ait_label]) and
  4781. not (tai_label(hp1).labsym.is_used) then
  4782. GetNextInstruction(hp1, hp1);
  4783. end;
  4784. TransferUsedRegs(TmpUsedRegs);
  4785. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4786. if not Assigned(hp1) or
  4787. (
  4788. not MatchInstruction(hp1, A_Jcc, A_SETcc, A_CMOVcc, []) and
  4789. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  4790. ) then
  4791. begin
  4792. { No more conditional jumps; conditional statement is no longer required }
  4793. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Test2Nop)', p);
  4794. RemoveCurrentP(p);
  4795. end;
  4796. Exit;
  4797. end;
  4798. end;
  4799. { Search for:
  4800. test $x,(reg/ref)
  4801. jne @lbl1
  4802. test $y,(reg/ref) (same register or reference)
  4803. jne @lbl1
  4804. Change to:
  4805. test $(x or y),(reg/ref)
  4806. jne @lbl1
  4807. (Note, this doesn't work with je instead of jne)
  4808. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4809. Also search for:
  4810. test $x,(reg/ref)
  4811. je @lbl1
  4812. test $y,(reg/ref)
  4813. je/jne @lbl2
  4814. If (x or y) = x, then the second jump is deterministic
  4815. }
  4816. if (
  4817. (
  4818. (taicpu(p).oper[0]^.typ = top_const) or
  4819. (
  4820. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4821. (taicpu(p).oper[0]^.typ = top_reg) and
  4822. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4823. )
  4824. ) and
  4825. MatchInstruction(hp1, A_JCC, [])
  4826. ) then
  4827. begin
  4828. if (taicpu(p).oper[0]^.typ = top_reg) and
  4829. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4830. FirstValue := -1
  4831. else
  4832. FirstValue := taicpu(p).oper[0]^.val;
  4833. { If we have several test/jne's in a row, it might be the case that
  4834. the second label doesn't go to the same location, but the one
  4835. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4836. so accommodate for this with a while loop.
  4837. }
  4838. hp1_dist := hp1;
  4839. if GetNextInstruction(hp1, p_dist) and
  4840. (p_dist.typ = ait_instruction) and
  4841. (
  4842. (
  4843. (taicpu(p_dist).opcode = A_TEST) and
  4844. (
  4845. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4846. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4847. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4848. )
  4849. ) or
  4850. (
  4851. { cmp 0,%reg = test %reg,%reg }
  4852. (taicpu(p_dist).opcode = A_CMP) and
  4853. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4854. )
  4855. ) and
  4856. { Make sure the destination operands are actually the same }
  4857. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4858. GetNextInstruction(p_dist, hp1_dist) and
  4859. MatchInstruction(hp1_dist, A_JCC, []) then
  4860. begin
  4861. if
  4862. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4863. (
  4864. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4865. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4866. ) then
  4867. SecondValue := -1
  4868. else
  4869. SecondValue := taicpu(p_dist).oper[0]^.val;
  4870. { If both of the TEST constants are identical, delete the second
  4871. TEST that is unnecessary. }
  4872. if (FirstValue = SecondValue) then
  4873. begin
  4874. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4875. RemoveInstruction(p_dist);
  4876. { Don't let the flags register become deallocated and reallocated between the jumps }
  4877. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4878. Result := True;
  4879. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4880. begin
  4881. { Since the second jump's condition is a subset of the first, we
  4882. know it will never branch because the first jump dominates it.
  4883. Get it out of the way now rather than wait for the jump
  4884. optimisations for a speed boost. }
  4885. if IsJumpToLabel(taicpu(hp1_dist)) then
  4886. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4887. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4888. RemoveInstruction(hp1_dist);
  4889. end
  4890. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4891. begin
  4892. { If the inverse of the first condition is a subset of the second,
  4893. the second one will definitely branch if the first one doesn't }
  4894. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4895. MakeUnconditional(taicpu(hp1_dist));
  4896. RemoveDeadCodeAfterJump(hp1_dist);
  4897. end;
  4898. Exit;
  4899. end;
  4900. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4901. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4902. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4903. then the second jump will never branch, so it can also be
  4904. removed regardless of where it goes }
  4905. (
  4906. (FirstValue = -1) or
  4907. (SecondValue = -1) or
  4908. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4909. ) then
  4910. begin
  4911. { Same jump location... can be a register since nothing's changed }
  4912. { If any of the entries are equivalent to test %reg,%reg, then the
  4913. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4914. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4915. if IsJumpToLabel(taicpu(hp1_dist)) then
  4916. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4917. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4918. RemoveInstruction(hp1_dist);
  4919. { Only remove the second test if no jumps or other conditional instructions follow }
  4920. TransferUsedRegs(TmpUsedRegs);
  4921. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4922. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4923. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4924. RemoveInstruction(p_dist);
  4925. Result := True;
  4926. Exit;
  4927. end;
  4928. end;
  4929. end;
  4930. { Search for:
  4931. test %reg,%reg
  4932. j(c1) @lbl1
  4933. ...
  4934. @lbl:
  4935. test %reg,%reg (same register)
  4936. j(c2) @lbl2
  4937. If c2 is a subset of c1, change to:
  4938. test %reg,%reg
  4939. j(c1) @lbl2
  4940. (@lbl1 may become a dead label as a result)
  4941. }
  4942. if (taicpu(p).oper[1]^.typ = top_reg) and
  4943. (taicpu(p).oper[0]^.typ = top_reg) and
  4944. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4945. MatchInstruction(hp1, A_JCC, []) and
  4946. IsJumpToLabel(taicpu(hp1)) then
  4947. begin
  4948. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4949. p_label := nil;
  4950. if Assigned(JumpLabel) then
  4951. p_label := getlabelwithsym(JumpLabel);
  4952. if Assigned(p_label) and
  4953. GetNextInstruction(p_label, p_dist) and
  4954. MatchInstruction(p_dist, A_TEST, []) and
  4955. { It's fine if the second test uses smaller sub-registers }
  4956. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4957. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4958. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4959. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4960. GetNextInstruction(p_dist, hp1_dist) and
  4961. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4962. begin
  4963. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4964. if JumpLabel = JumpLabel_dist then
  4965. { This is an infinite loop }
  4966. Exit;
  4967. { Best optimisation when the first condition is a subset (or equal) of the second }
  4968. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4969. begin
  4970. { Any registers used here will already be allocated }
  4971. if Assigned(JumpLabel) then
  4972. JumpLabel.DecRefs;
  4973. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4974. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  4975. Result := True;
  4976. Exit;
  4977. end;
  4978. end;
  4979. end;
  4980. end;
  4981. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4982. var
  4983. hp1, hp2: tai;
  4984. ActiveReg: TRegister;
  4985. OldOffset: asizeint;
  4986. ThisConst: TCGInt;
  4987. function RegDeallocated: Boolean;
  4988. begin
  4989. TransferUsedRegs(TmpUsedRegs);
  4990. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4991. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4992. end;
  4993. begin
  4994. result:=false;
  4995. hp1 := nil;
  4996. { replace
  4997. addX const,%reg1
  4998. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4999. dealloc %reg1
  5000. by
  5001. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  5002. }
  5003. if MatchOpType(taicpu(p),top_const,top_reg) then
  5004. begin
  5005. ActiveReg := taicpu(p).oper[1]^.reg;
  5006. { Ensures the entire register was updated }
  5007. if (taicpu(p).opsize >= S_L) and
  5008. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5009. MatchInstruction(hp1,A_LEA,[]) and
  5010. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5011. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5012. (
  5013. { Cover the case where the register in the reference is also the destination register }
  5014. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5015. (
  5016. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5017. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5018. RegDeallocated
  5019. )
  5020. ) then
  5021. begin
  5022. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5023. {$push}
  5024. {$R-}{$Q-}
  5025. { Explicitly disable overflow checking for these offset calculation
  5026. as those do not matter for the final result }
  5027. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5028. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5029. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5030. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5031. {$pop}
  5032. {$ifdef x86_64}
  5033. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5034. begin
  5035. { Overflow; abort }
  5036. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5037. end
  5038. else
  5039. {$endif x86_64}
  5040. begin
  5041. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  5042. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5043. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5044. RemoveCurrentP(p, hp1)
  5045. else
  5046. RemoveCurrentP(p);
  5047. result:=true;
  5048. Exit;
  5049. end;
  5050. end;
  5051. if (
  5052. { Save calling GetNextInstructionUsingReg again }
  5053. Assigned(hp1) or
  5054. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5055. ) and
  5056. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5057. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5058. begin
  5059. if taicpu(hp1).oper[0]^.typ = top_const then
  5060. begin
  5061. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  5062. if taicpu(hp1).opcode = A_ADD then
  5063. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5064. else
  5065. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5066. Result := True;
  5067. { Handle any overflows }
  5068. case taicpu(p).opsize of
  5069. S_B:
  5070. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5071. S_W:
  5072. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5073. S_L:
  5074. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5075. {$ifdef x86_64}
  5076. S_Q:
  5077. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5078. { Overflow; abort }
  5079. Result := False
  5080. else
  5081. taicpu(p).oper[0]^.val := ThisConst;
  5082. {$endif x86_64}
  5083. else
  5084. InternalError(2021102610);
  5085. end;
  5086. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5087. if Result then
  5088. begin
  5089. if (taicpu(p).oper[0]^.val < 0) and
  5090. (
  5091. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5092. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5093. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5094. ) then
  5095. begin
  5096. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  5097. taicpu(p).opcode := A_SUB;
  5098. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5099. end
  5100. else
  5101. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  5102. RemoveInstruction(hp1);
  5103. end;
  5104. end
  5105. else
  5106. begin
  5107. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  5108. TransferUsedRegs(TmpUsedRegs);
  5109. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5110. hp2 := p;
  5111. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5112. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5113. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5114. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5115. begin
  5116. { Move the constant addition to after the reg/ref addition to improve optimisation }
  5117. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  5118. Asml.Remove(p);
  5119. Asml.InsertAfter(p, hp1);
  5120. p := hp1;
  5121. Result := True;
  5122. Exit;
  5123. end;
  5124. end;
  5125. end;
  5126. if DoArithCombineOpt(p) then
  5127. Result:=true;
  5128. end;
  5129. end;
  5130. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  5131. var
  5132. hp1: tai;
  5133. ref: Integer;
  5134. saveref: treference;
  5135. Multiple: TCGInt;
  5136. Adjacent: Boolean;
  5137. begin
  5138. Result:=false;
  5139. { play save and throw an error if LEA uses a seg register prefix,
  5140. this is most likely an error somewhere else }
  5141. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  5142. internalerror(2022022001);
  5143. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  5144. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5145. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  5146. (
  5147. { do not mess with leas accessing the stack pointer
  5148. unless it's a null operation }
  5149. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  5150. (
  5151. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  5152. (taicpu(p).oper[0]^.ref^.offset = 0)
  5153. )
  5154. ) and
  5155. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  5156. begin
  5157. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  5158. begin
  5159. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  5160. begin
  5161. taicpu(p).opcode := A_MOV;
  5162. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  5163. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  5164. end
  5165. else
  5166. begin
  5167. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  5168. RemoveCurrentP(p);
  5169. end;
  5170. Result:=true;
  5171. exit;
  5172. end
  5173. else if (
  5174. { continue to use lea to adjust the stack pointer,
  5175. it is the recommended way, but only if not optimizing for size }
  5176. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5177. (cs_opt_size in current_settings.optimizerswitches)
  5178. ) and
  5179. { If the flags register is in use, don't change the instruction
  5180. to an ADD otherwise this will scramble the flags. [Kit] }
  5181. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5182. ConvertLEA(taicpu(p)) then
  5183. begin
  5184. Result:=true;
  5185. exit;
  5186. end;
  5187. end;
  5188. { Don't optimise if the stack or frame pointer is the destination register }
  5189. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5190. Exit;
  5191. if GetNextInstruction(p,hp1) and
  5192. (hp1.typ=ait_instruction) then
  5193. begin
  5194. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5195. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5196. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5197. begin
  5198. TransferUsedRegs(TmpUsedRegs);
  5199. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5200. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5201. begin
  5202. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5203. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5204. RemoveInstruction(hp1);
  5205. result:=true;
  5206. exit;
  5207. end;
  5208. end;
  5209. { changes
  5210. lea <ref1>, reg1
  5211. <op> ...,<ref. with reg1>,...
  5212. to
  5213. <op> ...,<ref1>,... }
  5214. { find a reference which uses reg1 }
  5215. 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
  5216. ref:=0
  5217. 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
  5218. ref:=1
  5219. else
  5220. ref:=-1;
  5221. if (ref<>-1) and
  5222. { reg1 must be either the base or the index }
  5223. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5224. begin
  5225. { reg1 can be removed from the reference }
  5226. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5227. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5228. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5229. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5230. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5231. else
  5232. Internalerror(2019111201);
  5233. { check if the can insert all data of the lea into the second instruction }
  5234. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5235. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5236. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5237. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5238. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5239. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5240. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5241. {$ifdef x86_64}
  5242. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5243. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5244. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5245. )
  5246. {$endif x86_64}
  5247. then
  5248. begin
  5249. { reg1 might not used by the second instruction after it is remove from the reference }
  5250. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5251. begin
  5252. TransferUsedRegs(TmpUsedRegs);
  5253. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5254. { reg1 is not updated so it might not be used afterwards }
  5255. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5256. begin
  5257. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5258. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5259. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5260. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5261. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5262. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5263. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5264. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5265. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5266. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5267. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5268. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5269. RemoveCurrentP(p, hp1);
  5270. result:=true;
  5271. exit;
  5272. end
  5273. end;
  5274. end;
  5275. { recover }
  5276. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5277. end;
  5278. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5279. if Adjacent or
  5280. { Check further ahead (up to 2 instructions ahead for -O2) }
  5281. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5282. begin
  5283. { Check common LEA/LEA conditions }
  5284. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5285. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  5286. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5287. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5288. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5289. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5290. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5291. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5292. (
  5293. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5294. calling it (since it calls GetNextInstruction) }
  5295. Adjacent or
  5296. (
  5297. (
  5298. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5299. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5300. ) and (
  5301. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5302. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5303. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5304. )
  5305. )
  5306. ) then
  5307. begin
  5308. { changes
  5309. lea (regX,scale), reg1
  5310. lea offset(reg1,reg1), reg1
  5311. to
  5312. lea offset(regX,scale*2), reg1
  5313. and
  5314. lea (regX,scale1), reg1
  5315. lea offset(reg1,scale2), reg1
  5316. to
  5317. lea offset(regX,scale1*scale2), reg1
  5318. ... so long as the final scale does not exceed 8
  5319. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5320. }
  5321. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5322. (taicpu(p).oper[0]^.ref^.offset = 0) and
  5323. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5324. (
  5325. (
  5326. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5327. ) or (
  5328. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5329. (
  5330. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5331. (
  5332. { RegUsedBetween always returns False if p and hp1 are adjacent }
  5333. Adjacent or
  5334. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  5335. )
  5336. )
  5337. )
  5338. ) and (
  5339. (
  5340. { lea (reg1,scale2), reg1 variant }
  5341. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  5342. (
  5343. (
  5344. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5345. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5346. ) or (
  5347. { lea (regX,regX), reg1 variant }
  5348. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5349. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5350. )
  5351. )
  5352. ) or (
  5353. { lea (reg1,reg1), reg1 variant }
  5354. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5355. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5356. )
  5357. ) then
  5358. begin
  5359. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5360. { Make everything homogeneous to make calculations easier }
  5361. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5362. begin
  5363. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5364. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5365. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5366. else
  5367. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5368. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5369. end;
  5370. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  5371. begin
  5372. { Just to prevent miscalculations }
  5373. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5374. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5375. else
  5376. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  5377. end
  5378. else
  5379. begin
  5380. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5381. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  5382. end;
  5383. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5384. RemoveCurrentP(p);
  5385. result:=true;
  5386. exit;
  5387. end
  5388. { changes
  5389. lea offset1(regX), reg1
  5390. lea offset2(reg1), reg1
  5391. to
  5392. lea offset1+offset2(regX), reg1 }
  5393. else if
  5394. (
  5395. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5396. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5397. ) or (
  5398. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5399. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5400. (
  5401. (
  5402. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5403. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5404. ) or (
  5405. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5406. (
  5407. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5408. (
  5409. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5410. (
  5411. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5412. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5413. )
  5414. )
  5415. )
  5416. )
  5417. )
  5418. ) then
  5419. begin
  5420. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5421. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5422. begin
  5423. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5424. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5425. { if the register is used as index and base, we have to increase for base as well
  5426. and adapt base }
  5427. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5428. begin
  5429. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5430. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5431. end;
  5432. end
  5433. else
  5434. begin
  5435. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5436. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5437. end;
  5438. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5439. begin
  5440. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5441. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5442. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5443. end;
  5444. RemoveCurrentP(p);
  5445. result:=true;
  5446. exit;
  5447. end;
  5448. end;
  5449. { Change:
  5450. leal/q $x(%reg1),%reg2
  5451. ...
  5452. shll/q $y,%reg2
  5453. To:
  5454. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5455. }
  5456. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5457. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5458. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5459. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5460. (taicpu(hp1).oper[0]^.val <= 3) then
  5461. begin
  5462. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5463. TransferUsedRegs(TmpUsedRegs);
  5464. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5465. if
  5466. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5467. (this works even if scalefactor is zero) }
  5468. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5469. { Ensure offset doesn't go out of bounds }
  5470. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5471. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5472. (
  5473. (
  5474. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5475. (
  5476. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5477. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5478. (
  5479. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5480. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5481. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5482. )
  5483. )
  5484. ) or (
  5485. (
  5486. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5487. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5488. ) and
  5489. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5490. )
  5491. ) then
  5492. begin
  5493. repeat
  5494. with taicpu(p).oper[0]^.ref^ do
  5495. begin
  5496. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5497. if index = base then
  5498. begin
  5499. if Multiple > 4 then
  5500. { Optimisation will no longer work because resultant
  5501. scale factor will exceed 8 }
  5502. Break;
  5503. base := NR_NO;
  5504. scalefactor := 2;
  5505. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5506. end
  5507. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5508. begin
  5509. { Scale factor only works on the index register }
  5510. index := base;
  5511. base := NR_NO;
  5512. end;
  5513. { For safety }
  5514. if scalefactor <= 1 then
  5515. begin
  5516. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5517. scalefactor := Multiple;
  5518. end
  5519. else
  5520. begin
  5521. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5522. scalefactor := scalefactor * Multiple;
  5523. end;
  5524. offset := offset * Multiple;
  5525. end;
  5526. RemoveInstruction(hp1);
  5527. Result := True;
  5528. Exit;
  5529. { This repeat..until loop exists for the benefit of Break }
  5530. until True;
  5531. end;
  5532. end;
  5533. end;
  5534. end;
  5535. end;
  5536. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5537. var
  5538. hp1 : tai;
  5539. SubInstr: Boolean;
  5540. ThisConst: TCGInt;
  5541. const
  5542. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5543. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5544. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5545. begin
  5546. Result := False;
  5547. if taicpu(p).oper[0]^.typ <> top_const then
  5548. { Should have been confirmed before calling }
  5549. InternalError(2021102601);
  5550. SubInstr := (taicpu(p).opcode = A_SUB);
  5551. if GetLastInstruction(p, hp1) and
  5552. (hp1.typ = ait_instruction) and
  5553. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5554. begin
  5555. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5556. { Bad size }
  5557. InternalError(2022042001);
  5558. case taicpu(hp1).opcode Of
  5559. A_INC:
  5560. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5561. begin
  5562. if SubInstr then
  5563. ThisConst := taicpu(p).oper[0]^.val - 1
  5564. else
  5565. ThisConst := taicpu(p).oper[0]^.val + 1;
  5566. end
  5567. else
  5568. Exit;
  5569. A_DEC:
  5570. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5571. begin
  5572. if SubInstr then
  5573. ThisConst := taicpu(p).oper[0]^.val + 1
  5574. else
  5575. ThisConst := taicpu(p).oper[0]^.val - 1;
  5576. end
  5577. else
  5578. Exit;
  5579. A_SUB:
  5580. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5581. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5582. begin
  5583. if SubInstr then
  5584. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5585. else
  5586. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5587. end
  5588. else
  5589. Exit;
  5590. A_ADD:
  5591. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5592. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5593. begin
  5594. if SubInstr then
  5595. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5596. else
  5597. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5598. end
  5599. else
  5600. Exit;
  5601. else
  5602. Exit;
  5603. end;
  5604. { Check that the values are in range }
  5605. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5606. { Overflow; abort }
  5607. Exit;
  5608. if (ThisConst = 0) then
  5609. begin
  5610. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5611. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5612. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5613. RemoveInstruction(hp1);
  5614. hp1 := tai(p.next);
  5615. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5616. if not GetLastInstruction(hp1, p) then
  5617. p := hp1;
  5618. end
  5619. else
  5620. begin
  5621. if taicpu(hp1).opercnt=1 then
  5622. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5623. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5624. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5625. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5626. else
  5627. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5628. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5629. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5630. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5631. RemoveInstruction(hp1);
  5632. taicpu(p).loadconst(0, ThisConst);
  5633. end;
  5634. Result := True;
  5635. end;
  5636. end;
  5637. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  5638. begin
  5639. Result := False;
  5640. if UpdateTmpUsedRegs then
  5641. TransferUsedRegs(TmpUsedRegs);
  5642. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5643. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5644. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5645. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5646. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5647. (
  5648. (
  5649. (taicpu(hp1).opcode = A_TEST)
  5650. ) or (
  5651. (taicpu(hp1).opcode = A_CMP) and
  5652. { A sanity check more than anything }
  5653. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5654. )
  5655. ) then
  5656. begin
  5657. { change
  5658. mov mem, %reg
  5659. cmp/test x, %reg / test %reg,%reg
  5660. (reg deallocated)
  5661. to
  5662. cmp/test x, mem / cmp 0, mem
  5663. }
  5664. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5665. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5666. begin
  5667. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5668. if (taicpu(hp1).opcode = A_TEST) and
  5669. (
  5670. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5671. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5672. ) then
  5673. begin
  5674. taicpu(hp1).opcode := A_CMP;
  5675. taicpu(hp1).loadconst(0, 0);
  5676. end;
  5677. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5678. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5679. RemoveCurrentP(p, hp1);
  5680. Result := True;
  5681. Exit;
  5682. end;
  5683. end;
  5684. end;
  5685. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5686. var
  5687. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5688. ThisReg, SecondReg: TRegister;
  5689. JumpLoc: TAsmLabel;
  5690. NewSize: TOpSize;
  5691. begin
  5692. Result := False;
  5693. {
  5694. Convert:
  5695. j<c> .L1
  5696. .L2:
  5697. mov 1,reg
  5698. jmp .L3 (or ret, although it might not be a RET yet)
  5699. .L1:
  5700. mov 0,reg
  5701. jmp .L3 (or ret)
  5702. ( As long as .L3 <> .L1 or .L2)
  5703. To:
  5704. mov 0,reg
  5705. set<not(c)> reg
  5706. jmp .L3 (or ret)
  5707. .L2:
  5708. mov 1,reg
  5709. jmp .L3 (or ret)
  5710. .L1:
  5711. mov 0,reg
  5712. jmp .L3 (or ret)
  5713. }
  5714. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5715. Exit;
  5716. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5717. if GetNextInstruction(hp_label, hp2) and
  5718. MatchInstruction(hp2,A_MOV,[]) and
  5719. (taicpu(hp2).oper[0]^.typ = top_const) and
  5720. (
  5721. (
  5722. (taicpu(hp2).oper[1]^.typ = top_reg)
  5723. {$ifdef i386}
  5724. { Under i386, ESI, EDI, EBP and ESP
  5725. don't have an 8-bit representation }
  5726. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5727. {$endif i386}
  5728. ) or (
  5729. {$ifdef i386}
  5730. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5731. {$endif i386}
  5732. (taicpu(hp2).opsize = S_B)
  5733. )
  5734. ) and
  5735. GetNextInstruction(hp2, hp3) and
  5736. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5737. (
  5738. (taicpu(hp3).opcode=A_RET) or
  5739. (
  5740. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5741. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5742. )
  5743. ) and
  5744. GetNextInstruction(hp3, hp4) and
  5745. SkipAligns(hp4, hp4) and
  5746. (hp4.typ=ait_label) and
  5747. (tai_label(hp4).labsym=JumpLoc) and
  5748. (
  5749. not (cs_opt_size in current_settings.optimizerswitches) or
  5750. { If the initial jump is the label's only reference, then it will
  5751. become a dead label if the other conditions are met and hence
  5752. remove at least 2 instructions, including a jump }
  5753. (JumpLoc.getrefs = 1)
  5754. ) and
  5755. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5756. that will be optimised out }
  5757. GetNextInstruction(hp4, hp5) and
  5758. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5759. (taicpu(hp5).oper[0]^.typ = top_const) and
  5760. (
  5761. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5762. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5763. ) and
  5764. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5765. GetNextInstruction(hp5,hp6) and
  5766. (
  5767. (hp6.typ<>ait_label) or
  5768. SkipLabels(hp6, hp6)
  5769. ) and
  5770. (hp6.typ=ait_instruction) then
  5771. begin
  5772. { First, let's look at the two jumps that are hp3 and hp6 }
  5773. if not
  5774. (
  5775. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5776. (
  5777. (taicpu(hp6).opcode=A_RET) or
  5778. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5779. )
  5780. ) then
  5781. { If condition is False, then the JMP/RET instructions matched conventionally }
  5782. begin
  5783. { See if one of the jumps can be instantly converted into a RET }
  5784. if (taicpu(hp3).opcode=A_JMP) then
  5785. begin
  5786. { Reuse hp5 }
  5787. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5788. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5789. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5790. Exit;
  5791. if MatchInstruction(hp5, A_RET, []) then
  5792. begin
  5793. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5794. ConvertJumpToRET(hp3, hp5);
  5795. Result := True;
  5796. end
  5797. else
  5798. Exit;
  5799. end;
  5800. if (taicpu(hp6).opcode=A_JMP) then
  5801. begin
  5802. { Reuse hp5 }
  5803. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5804. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5805. Exit;
  5806. if MatchInstruction(hp5, A_RET, []) then
  5807. begin
  5808. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5809. ConvertJumpToRET(hp6, hp5);
  5810. Result := True;
  5811. end
  5812. else
  5813. Exit;
  5814. end;
  5815. if not
  5816. (
  5817. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5818. (
  5819. (taicpu(hp6).opcode=A_RET) or
  5820. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5821. )
  5822. ) then
  5823. { Still doesn't match }
  5824. Exit;
  5825. end;
  5826. if (taicpu(hp2).oper[0]^.val = 1) then
  5827. begin
  5828. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5829. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5830. end
  5831. else
  5832. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5833. if taicpu(hp2).opsize=S_B then
  5834. begin
  5835. if taicpu(hp2).oper[1]^.typ = top_reg then
  5836. begin
  5837. SecondReg := taicpu(hp2).oper[1]^.reg;
  5838. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  5839. end
  5840. else
  5841. begin
  5842. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5843. SecondReg := NR_NO;
  5844. end;
  5845. hp_pos := p;
  5846. hp_allocstart := hp4;
  5847. end
  5848. else
  5849. begin
  5850. { Will be a register because the size can't be S_B otherwise }
  5851. SecondReg:=taicpu(hp2).oper[1]^.reg;
  5852. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  5853. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5854. if (cs_opt_size in current_settings.optimizerswitches) then
  5855. begin
  5856. { Favour using MOVZX when optimising for size }
  5857. case taicpu(hp2).opsize of
  5858. S_W:
  5859. NewSize := S_BW;
  5860. S_L:
  5861. NewSize := S_BL;
  5862. {$ifdef x86_64}
  5863. S_Q:
  5864. begin
  5865. NewSize := S_BL;
  5866. { Will implicitly zero-extend to 64-bit }
  5867. setsubreg(SecondReg, R_SUBD);
  5868. end;
  5869. {$endif x86_64}
  5870. else
  5871. InternalError(2022101301);
  5872. end;
  5873. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  5874. { Inserting it right before p will guarantee that the flags are also tracked }
  5875. Asml.InsertBefore(hp5, p);
  5876. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  5877. hp_pos := hp5;
  5878. hp_allocstart := hp4;
  5879. end
  5880. else
  5881. begin
  5882. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  5883. { Inserting it right before p will guarantee that the flags are also tracked }
  5884. Asml.InsertBefore(hp5, p);
  5885. hp_pos := p;
  5886. hp_allocstart := hp5;
  5887. end;
  5888. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  5889. end;
  5890. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  5891. taicpu(hp4).condition := taicpu(p).condition;
  5892. asml.InsertBefore(hp4, hp_pos);
  5893. if taicpu(hp3).is_jmp then
  5894. begin
  5895. JumpLoc.decrefs;
  5896. MakeUnconditional(taicpu(p));
  5897. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5898. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5899. end
  5900. else
  5901. ConvertJumpToRET(p, hp3);
  5902. if SecondReg <> NR_NO then
  5903. { Ensure the destination register is allocated over this region }
  5904. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  5905. if (JumpLoc.getrefs = 0) then
  5906. RemoveDeadCodeAfterJump(hp3);
  5907. Result:=true;
  5908. exit;
  5909. end;
  5910. end;
  5911. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5912. var
  5913. hp1, hp2: tai;
  5914. ActiveReg: TRegister;
  5915. OldOffset: asizeint;
  5916. ThisConst: TCGInt;
  5917. function RegDeallocated: Boolean;
  5918. begin
  5919. TransferUsedRegs(TmpUsedRegs);
  5920. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5921. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5922. end;
  5923. begin
  5924. Result:=false;
  5925. hp1 := nil;
  5926. { replace
  5927. subX const,%reg1
  5928. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5929. dealloc %reg1
  5930. by
  5931. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5932. }
  5933. if MatchOpType(taicpu(p),top_const,top_reg) then
  5934. begin
  5935. ActiveReg := taicpu(p).oper[1]^.reg;
  5936. { Ensures the entire register was updated }
  5937. if (taicpu(p).opsize >= S_L) and
  5938. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5939. MatchInstruction(hp1,A_LEA,[]) and
  5940. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5941. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5942. (
  5943. { Cover the case where the register in the reference is also the destination register }
  5944. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5945. (
  5946. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5947. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5948. RegDeallocated
  5949. )
  5950. ) then
  5951. begin
  5952. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5953. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5954. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5955. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5956. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5957. {$ifdef x86_64}
  5958. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5959. begin
  5960. { Overflow; abort }
  5961. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5962. end
  5963. else
  5964. {$endif x86_64}
  5965. begin
  5966. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5967. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5968. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5969. RemoveCurrentP(p, hp1)
  5970. else
  5971. RemoveCurrentP(p);
  5972. result:=true;
  5973. Exit;
  5974. end;
  5975. end;
  5976. if (
  5977. { Save calling GetNextInstructionUsingReg again }
  5978. Assigned(hp1) or
  5979. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5980. ) and
  5981. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5982. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5983. begin
  5984. if taicpu(hp1).oper[0]^.typ = top_const then
  5985. begin
  5986. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5987. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5988. Result := True;
  5989. { Handle any overflows }
  5990. case taicpu(p).opsize of
  5991. S_B:
  5992. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5993. S_W:
  5994. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5995. S_L:
  5996. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5997. {$ifdef x86_64}
  5998. S_Q:
  5999. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  6000. { Overflow; abort }
  6001. Result := False
  6002. else
  6003. taicpu(p).oper[0]^.val := ThisConst;
  6004. {$endif x86_64}
  6005. else
  6006. InternalError(2021102611);
  6007. end;
  6008. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  6009. if Result then
  6010. begin
  6011. if (taicpu(p).oper[0]^.val < 0) and
  6012. (
  6013. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  6014. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  6015. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  6016. ) then
  6017. begin
  6018. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  6019. taicpu(p).opcode := A_SUB;
  6020. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  6021. end
  6022. else
  6023. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  6024. RemoveInstruction(hp1);
  6025. end;
  6026. end
  6027. else
  6028. begin
  6029. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  6030. TransferUsedRegs(TmpUsedRegs);
  6031. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6032. hp2 := p;
  6033. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  6034. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  6035. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6036. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  6037. begin
  6038. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  6039. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  6040. Asml.Remove(p);
  6041. Asml.InsertAfter(p, hp1);
  6042. p := hp1;
  6043. Result := True;
  6044. Exit;
  6045. end;
  6046. end;
  6047. end;
  6048. { * change "subl $2, %esp; pushw x" to "pushl x"}
  6049. { * change "sub/add const1, reg" or "dec reg" followed by
  6050. "sub const2, reg" to one "sub ..., reg" }
  6051. {$ifdef i386}
  6052. if (taicpu(p).oper[0]^.val = 2) and
  6053. (ActiveReg = NR_ESP) and
  6054. { Don't do the sub/push optimization if the sub }
  6055. { comes from setting up the stack frame (JM) }
  6056. (not(GetLastInstruction(p,hp1)) or
  6057. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  6058. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  6059. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  6060. begin
  6061. hp1 := tai(p.next);
  6062. while Assigned(hp1) and
  6063. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  6064. not RegReadByInstruction(NR_ESP,hp1) and
  6065. not RegModifiedByInstruction(NR_ESP,hp1) do
  6066. hp1 := tai(hp1.next);
  6067. if Assigned(hp1) and
  6068. MatchInstruction(hp1,A_PUSH,[S_W]) then
  6069. begin
  6070. taicpu(hp1).changeopsize(S_L);
  6071. if taicpu(hp1).oper[0]^.typ=top_reg then
  6072. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  6073. hp1 := tai(p.next);
  6074. RemoveCurrentp(p, hp1);
  6075. Result:=true;
  6076. exit;
  6077. end;
  6078. end;
  6079. {$endif i386}
  6080. if DoArithCombineOpt(p) then
  6081. Result:=true;
  6082. end;
  6083. end;
  6084. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  6085. var
  6086. TmpBool1,TmpBool2 : Boolean;
  6087. tmpref : treference;
  6088. hp1,hp2: tai;
  6089. mask, shiftval: tcgint;
  6090. begin
  6091. Result:=false;
  6092. { All these optimisations work on "shl/sal const,%reg" }
  6093. if not MatchOpType(taicpu(p),top_const,top_reg) then
  6094. Exit;
  6095. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  6096. (taicpu(p).oper[0]^.val <= 3) then
  6097. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  6098. begin
  6099. { should we check the next instruction? }
  6100. TmpBool1 := True;
  6101. { have we found an add/sub which could be
  6102. integrated in the lea? }
  6103. TmpBool2 := False;
  6104. reference_reset(tmpref,2,[]);
  6105. TmpRef.index := taicpu(p).oper[1]^.reg;
  6106. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6107. while TmpBool1 and
  6108. GetNextInstruction(p, hp1) and
  6109. (tai(hp1).typ = ait_instruction) and
  6110. ((((taicpu(hp1).opcode = A_ADD) or
  6111. (taicpu(hp1).opcode = A_SUB)) and
  6112. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  6113. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  6114. (((taicpu(hp1).opcode = A_INC) or
  6115. (taicpu(hp1).opcode = A_DEC)) and
  6116. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6117. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  6118. ((taicpu(hp1).opcode = A_LEA) and
  6119. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  6120. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  6121. (not GetNextInstruction(hp1,hp2) or
  6122. not instrReadsFlags(hp2)) Do
  6123. begin
  6124. TmpBool1 := False;
  6125. if taicpu(hp1).opcode=A_LEA then
  6126. begin
  6127. if (TmpRef.base = NR_NO) and
  6128. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  6129. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  6130. { Segment register isn't a concern here }
  6131. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  6132. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  6133. begin
  6134. TmpBool1 := True;
  6135. TmpBool2 := True;
  6136. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  6137. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  6138. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  6139. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  6140. RemoveInstruction(hp1);
  6141. end
  6142. end
  6143. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  6144. begin
  6145. TmpBool1 := True;
  6146. TmpBool2 := True;
  6147. case taicpu(hp1).opcode of
  6148. A_ADD:
  6149. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6150. A_SUB:
  6151. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  6152. else
  6153. internalerror(2019050536);
  6154. end;
  6155. RemoveInstruction(hp1);
  6156. end
  6157. else
  6158. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  6159. (((taicpu(hp1).opcode = A_ADD) and
  6160. (TmpRef.base = NR_NO)) or
  6161. (taicpu(hp1).opcode = A_INC) or
  6162. (taicpu(hp1).opcode = A_DEC)) then
  6163. begin
  6164. TmpBool1 := True;
  6165. TmpBool2 := True;
  6166. case taicpu(hp1).opcode of
  6167. A_ADD:
  6168. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  6169. A_INC:
  6170. inc(TmpRef.offset);
  6171. A_DEC:
  6172. dec(TmpRef.offset);
  6173. else
  6174. internalerror(2019050535);
  6175. end;
  6176. RemoveInstruction(hp1);
  6177. end;
  6178. end;
  6179. if TmpBool2
  6180. {$ifndef x86_64}
  6181. or
  6182. ((current_settings.optimizecputype < cpu_Pentium2) and
  6183. (taicpu(p).oper[0]^.val <= 3) and
  6184. not(cs_opt_size in current_settings.optimizerswitches))
  6185. {$endif x86_64}
  6186. then
  6187. begin
  6188. if not(TmpBool2) and
  6189. (taicpu(p).oper[0]^.val=1) then
  6190. begin
  6191. taicpu(p).opcode := A_ADD;
  6192. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6193. end
  6194. else
  6195. begin
  6196. taicpu(p).opcode := A_LEA;
  6197. taicpu(p).loadref(0, TmpRef);
  6198. end;
  6199. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6200. Result := True;
  6201. end;
  6202. end
  6203. {$ifndef x86_64}
  6204. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6205. begin
  6206. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6207. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6208. (unlike shl, which is only Tairable in the U pipe) }
  6209. if taicpu(p).oper[0]^.val=1 then
  6210. begin
  6211. taicpu(p).opcode := A_ADD;
  6212. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6213. Result := True;
  6214. end
  6215. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6216. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6217. else if (taicpu(p).opsize = S_L) and
  6218. (taicpu(p).oper[0]^.val<= 3) then
  6219. begin
  6220. reference_reset(tmpref,2,[]);
  6221. TmpRef.index := taicpu(p).oper[1]^.reg;
  6222. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6223. taicpu(p).opcode := A_LEA;
  6224. taicpu(p).loadref(0, TmpRef);
  6225. Result := True;
  6226. end;
  6227. end
  6228. {$endif x86_64}
  6229. else if
  6230. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6231. (
  6232. (
  6233. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6234. SetAndTest(hp1, hp2)
  6235. {$ifdef x86_64}
  6236. ) or
  6237. (
  6238. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6239. GetNextInstruction(hp1, hp2) and
  6240. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6241. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6242. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6243. {$endif x86_64}
  6244. )
  6245. ) and
  6246. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6247. begin
  6248. { Change:
  6249. shl x, %reg1
  6250. mov -(1<<x), %reg2
  6251. and %reg2, %reg1
  6252. Or:
  6253. shl x, %reg1
  6254. and -(1<<x), %reg1
  6255. To just:
  6256. shl x, %reg1
  6257. Since the and operation only zeroes bits that are already zero from the shl operation
  6258. }
  6259. case taicpu(p).oper[0]^.val of
  6260. 8:
  6261. mask:=$FFFFFFFFFFFFFF00;
  6262. 16:
  6263. mask:=$FFFFFFFFFFFF0000;
  6264. 32:
  6265. mask:=$FFFFFFFF00000000;
  6266. 63:
  6267. { Constant pre-calculated to prevent overflow errors with Int64 }
  6268. mask:=$8000000000000000;
  6269. else
  6270. begin
  6271. if taicpu(p).oper[0]^.val >= 64 then
  6272. { Shouldn't happen realistically, since the register
  6273. is guaranteed to be set to zero at this point }
  6274. mask := 0
  6275. else
  6276. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6277. end;
  6278. end;
  6279. if taicpu(hp1).oper[0]^.val = mask then
  6280. begin
  6281. { Everything checks out, perform the optimisation, as long as
  6282. the FLAGS register isn't being used}
  6283. TransferUsedRegs(TmpUsedRegs);
  6284. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6285. {$ifdef x86_64}
  6286. if (hp1 <> hp2) then
  6287. begin
  6288. { "shl/mov/and" version }
  6289. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6290. { Don't do the optimisation if the FLAGS register is in use }
  6291. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6292. begin
  6293. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6294. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6295. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6296. begin
  6297. RemoveInstruction(hp1);
  6298. Result := True;
  6299. end;
  6300. { Only set Result to True if the 'mov' instruction was removed }
  6301. RemoveInstruction(hp2);
  6302. end;
  6303. end
  6304. else
  6305. {$endif x86_64}
  6306. begin
  6307. { "shl/and" version }
  6308. { Don't do the optimisation if the FLAGS register is in use }
  6309. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6310. begin
  6311. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6312. RemoveInstruction(hp1);
  6313. Result := True;
  6314. end;
  6315. end;
  6316. Exit;
  6317. end
  6318. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6319. begin
  6320. { Even if the mask doesn't allow for its removal, we might be
  6321. able to optimise the mask for the "shl/and" version, which
  6322. may permit other peephole optimisations }
  6323. {$ifdef DEBUG_AOPTCPU}
  6324. mask := taicpu(hp1).oper[0]^.val and mask;
  6325. if taicpu(hp1).oper[0]^.val <> mask then
  6326. begin
  6327. DebugMsg(
  6328. SPeepholeOptimization +
  6329. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6330. ' to $' + debug_tostr(mask) +
  6331. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6332. taicpu(hp1).oper[0]^.val := mask;
  6333. end;
  6334. {$else DEBUG_AOPTCPU}
  6335. { If debugging is off, just set the operand even if it's the same }
  6336. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6337. {$endif DEBUG_AOPTCPU}
  6338. end;
  6339. end;
  6340. {
  6341. change
  6342. shl/sal const,reg
  6343. <op> ...(...,reg,1),...
  6344. into
  6345. <op> ...(...,reg,1 shl const),...
  6346. if const in 1..3
  6347. }
  6348. if MatchOpType(taicpu(p), top_const, top_reg) and
  6349. (taicpu(p).oper[0]^.val in [1..3]) and
  6350. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6351. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6352. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6353. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6354. MatchOpType(taicpu(hp1),top_ref))
  6355. ) and
  6356. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6357. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6358. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6359. begin
  6360. TransferUsedRegs(TmpUsedRegs);
  6361. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6362. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6363. begin
  6364. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6365. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6366. RemoveCurrentP(p);
  6367. Result:=true;
  6368. exit;
  6369. end;
  6370. end;
  6371. if MatchOpType(taicpu(p), top_const, top_reg) and
  6372. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6373. MatchInstruction(hp1,A_SHL,[taicpu(p).opsize]) and
  6374. MatchOpType(taicpu(hp1),top_const,top_reg) and
  6375. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[1]^.reg) then
  6376. begin
  6377. shiftval:=taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val;
  6378. if ((taicpu(p).opsize=S_B) and (shiftval>7)) or
  6379. ((taicpu(p).opsize=S_W) and (shiftval>15)) or
  6380. {$ifdef x86_64}
  6381. ((taicpu(p).opsize=S_Q) and (shiftval>63)) or
  6382. {$endif x86_64}
  6383. ((taicpu(p).opsize=S_L) and (shiftval>31)) then
  6384. begin
  6385. DebugMsg(SPeepholeOptimization + 'ShlShl2Mov', p);
  6386. taicpu(hp1).opcode:=A_MOV;
  6387. taicpu(hp1).oper[0]^.val:=0;
  6388. end
  6389. else
  6390. begin
  6391. DebugMsg(SPeepholeOptimization + 'ShlShl2Shl', p);
  6392. taicpu(hp1).oper[0]^.val:=shiftval;
  6393. end;
  6394. RemoveCurrentP(p);
  6395. Result:=true;
  6396. exit;
  6397. end;
  6398. end;
  6399. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6400. begin
  6401. case shr_size of
  6402. S_B:
  6403. { No valid combinations }
  6404. Result := False;
  6405. S_W:
  6406. Result := (Shift >= 8) and (movz_size = S_BW);
  6407. S_L:
  6408. Result :=
  6409. (Shift >= 24) { Any opsize is valid for this shift } or
  6410. ((Shift >= 16) and (movz_size = S_WL));
  6411. {$ifdef x86_64}
  6412. S_Q:
  6413. Result :=
  6414. (Shift >= 56) { Any opsize is valid for this shift } or
  6415. ((Shift >= 48) and (movz_size = S_WL));
  6416. {$endif x86_64}
  6417. else
  6418. InternalError(2022081510);
  6419. end;
  6420. end;
  6421. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6422. var
  6423. hp1, hp2: tai;
  6424. Shift: TCGInt;
  6425. LimitSize: Topsize;
  6426. DoNotMerge: Boolean;
  6427. begin
  6428. Result := False;
  6429. { All these optimisations work on "shr const,%reg" }
  6430. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6431. Exit;
  6432. DoNotMerge := False;
  6433. Shift := taicpu(p).oper[0]^.val;
  6434. LimitSize := taicpu(p).opsize;
  6435. hp1 := p;
  6436. repeat
  6437. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6438. Exit;
  6439. case taicpu(hp1).opcode of
  6440. A_TEST, A_CMP, A_Jcc:
  6441. { Skip over conditional jumps and relevant comparisons }
  6442. Continue;
  6443. A_MOVZX:
  6444. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6445. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6446. begin
  6447. { Since the original register is being read as is, subsequent
  6448. SHRs must not be merged at this point }
  6449. DoNotMerge := True;
  6450. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6451. begin
  6452. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6453. begin
  6454. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6455. taicpu(hp1).opcode := A_MOV;
  6456. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6457. case taicpu(hp1).opsize of
  6458. S_BW:
  6459. taicpu(hp1).opsize := S_W;
  6460. S_BL, S_WL:
  6461. taicpu(hp1).opsize := S_L;
  6462. else
  6463. InternalError(2022081503);
  6464. end;
  6465. { p itself hasn't changed, so no need to set Result to True }
  6466. Include(OptsToCheck, aoc_ForceNewIteration);
  6467. { See if there's anything afterwards that can be
  6468. optimised, since the input register hasn't changed }
  6469. Continue;
  6470. end;
  6471. { NOTE: If the MOVZX instruction reads and writes the same
  6472. register, defer this to the post-peephole optimisation stage }
  6473. Exit;
  6474. end;
  6475. end;
  6476. A_SHL, A_SAL, A_SHR:
  6477. if (taicpu(hp1).opsize <= LimitSize) and
  6478. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6479. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6480. begin
  6481. { Make sure the sizes don't exceed the register size limit
  6482. (measured by the shift value falling below the limit) }
  6483. if taicpu(hp1).opsize < LimitSize then
  6484. LimitSize := taicpu(hp1).opsize;
  6485. if taicpu(hp1).opcode = A_SHR then
  6486. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6487. else
  6488. begin
  6489. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6490. DoNotMerge := True;
  6491. end;
  6492. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6493. Exit;
  6494. { Since we've established that the combined shift is within
  6495. limits, we can actually combine the adjacent SHR
  6496. instructions even if they're different sizes }
  6497. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6498. begin
  6499. hp2 := tai(hp1.Previous);
  6500. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6501. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6502. RemoveInstruction(hp1);
  6503. hp1 := hp2;
  6504. { Though p has changed, only the constant has, and its
  6505. effects can still be detected on the next iteration of
  6506. the repeat..until loop }
  6507. Include(OptsToCheck, aoc_ForceNewIteration);
  6508. end;
  6509. { Move onto the next instruction }
  6510. Continue;
  6511. end;
  6512. else
  6513. ;
  6514. end;
  6515. Break;
  6516. until False;
  6517. end;
  6518. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6519. var
  6520. CurrentRef: TReference;
  6521. FullReg: TRegister;
  6522. hp1, hp2: tai;
  6523. begin
  6524. Result := False;
  6525. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6526. Exit;
  6527. { We assume you've checked if the operand is actually a reference by
  6528. this point. If it isn't, you'll most likely get an access violation }
  6529. CurrentRef := first_mov.oper[1]^.ref^;
  6530. { Memory must be aligned }
  6531. if (CurrentRef.offset mod 4) <> 0 then
  6532. Exit;
  6533. Inc(CurrentRef.offset);
  6534. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6535. if MatchOperand(second_mov.oper[0]^, 0) and
  6536. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6537. GetNextInstruction(second_mov, hp1) and
  6538. (hp1.typ = ait_instruction) and
  6539. (taicpu(hp1).opcode = A_MOV) and
  6540. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6541. (taicpu(hp1).oper[0]^.val = 0) then
  6542. begin
  6543. Inc(CurrentRef.offset);
  6544. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6545. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6546. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6547. begin
  6548. case taicpu(hp1).opsize of
  6549. S_B:
  6550. if GetNextInstruction(hp1, hp2) and
  6551. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6552. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6553. (taicpu(hp2).oper[0]^.val = 0) then
  6554. begin
  6555. Inc(CurrentRef.offset);
  6556. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6557. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6558. (taicpu(hp2).opsize = S_B) then
  6559. begin
  6560. RemoveInstruction(hp1);
  6561. RemoveInstruction(hp2);
  6562. first_mov.opsize := S_L;
  6563. if first_mov.oper[0]^.typ = top_reg then
  6564. begin
  6565. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6566. { Reuse second_mov as a MOVZX instruction }
  6567. second_mov.opcode := A_MOVZX;
  6568. second_mov.opsize := S_BL;
  6569. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6570. second_mov.loadreg(1, FullReg);
  6571. first_mov.oper[0]^.reg := FullReg;
  6572. asml.Remove(second_mov);
  6573. asml.InsertBefore(second_mov, first_mov);
  6574. end
  6575. else
  6576. { It's a value }
  6577. begin
  6578. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6579. RemoveInstruction(second_mov);
  6580. end;
  6581. Result := True;
  6582. Exit;
  6583. end;
  6584. end;
  6585. S_W:
  6586. begin
  6587. RemoveInstruction(hp1);
  6588. first_mov.opsize := S_L;
  6589. if first_mov.oper[0]^.typ = top_reg then
  6590. begin
  6591. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6592. { Reuse second_mov as a MOVZX instruction }
  6593. second_mov.opcode := A_MOVZX;
  6594. second_mov.opsize := S_BL;
  6595. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6596. second_mov.loadreg(1, FullReg);
  6597. first_mov.oper[0]^.reg := FullReg;
  6598. asml.Remove(second_mov);
  6599. asml.InsertBefore(second_mov, first_mov);
  6600. end
  6601. else
  6602. { It's a value }
  6603. begin
  6604. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6605. RemoveInstruction(second_mov);
  6606. end;
  6607. Result := True;
  6608. Exit;
  6609. end;
  6610. else
  6611. ;
  6612. end;
  6613. end;
  6614. end;
  6615. end;
  6616. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6617. { returns true if a "continue" should be done after this optimization }
  6618. var
  6619. hp1, hp2, hp3: tai;
  6620. begin
  6621. Result := false;
  6622. hp3 := nil;
  6623. if MatchOpType(taicpu(p),top_ref) and
  6624. GetNextInstruction(p, hp1) and
  6625. (hp1.typ = ait_instruction) and
  6626. (((taicpu(hp1).opcode = A_FLD) and
  6627. (taicpu(p).opcode = A_FSTP)) or
  6628. ((taicpu(p).opcode = A_FISTP) and
  6629. (taicpu(hp1).opcode = A_FILD))) and
  6630. MatchOpType(taicpu(hp1),top_ref) and
  6631. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6632. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6633. begin
  6634. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6635. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6636. GetNextInstruction(hp1, hp2) and
  6637. (((hp2.typ = ait_instruction) and
  6638. IsExitCode(hp2) and
  6639. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6640. not(assigned(current_procinfo.procdef.funcretsym) and
  6641. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6642. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6643. { fstp <temp>
  6644. fld <temp>
  6645. <dealloc> <temp>
  6646. }
  6647. ((taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6648. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6649. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp1.next)),hp2) and
  6650. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6651. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6652. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6653. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6654. )
  6655. )
  6656. ) then
  6657. begin
  6658. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6659. RemoveInstruction(hp1);
  6660. RemoveCurrentP(p, hp2);
  6661. { first case: exit code }
  6662. if hp2.typ = ait_instruction then
  6663. RemoveLastDeallocForFuncRes(p);
  6664. Result := true;
  6665. end
  6666. else
  6667. { we can do this only in fast math mode as fstp is rounding ...
  6668. ... still disabled as it breaks the compiler and/or rtl }
  6669. if { (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6670. { ... or if another fstp equal to the first one follows }
  6671. GetNextInstruction(hp1,hp2) and
  6672. (hp2.typ = ait_instruction) and
  6673. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6674. (taicpu(p).opsize=taicpu(hp2).opsize) then
  6675. begin
  6676. if (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6677. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6678. SetAndTest(FindTempDeAlloc(taicpu(p).oper[0]^.ref^.offset,tai(hp2.next)),hp3) and
  6679. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  6680. (tai_tempalloc(hp3).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6681. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp3).tempsize=16)) or
  6682. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp3).tempsize=8)) or
  6683. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp3).tempsize=4))
  6684. ) then
  6685. begin
  6686. DebugMsg(SPeepholeOptimization + 'FstpFldFstp2Fstp',p);
  6687. RemoveCurrentP(p,hp2);
  6688. RemoveInstruction(hp1);
  6689. Result := true;
  6690. end
  6691. else if { fst can't store an extended/comp value }
  6692. (taicpu(p).opsize <> S_FX) and
  6693. (taicpu(p).opsize <> S_IQ) then
  6694. begin
  6695. if (taicpu(p).opcode = A_FSTP) then
  6696. taicpu(p).opcode := A_FST
  6697. else
  6698. taicpu(p).opcode := A_FIST;
  6699. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6700. RemoveInstruction(hp1);
  6701. Result := true;
  6702. end;
  6703. end;
  6704. end;
  6705. end;
  6706. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6707. var
  6708. hp1, hp2, hp3: tai;
  6709. begin
  6710. result:=false;
  6711. if MatchOpType(taicpu(p),top_reg) and
  6712. GetNextInstruction(p, hp1) and
  6713. (hp1.typ = Ait_Instruction) and
  6714. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6715. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6716. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6717. { change to
  6718. fld reg fxxx reg,st
  6719. fxxxp st, st1 (hp1)
  6720. Remark: non commutative operations must be reversed!
  6721. }
  6722. begin
  6723. case taicpu(hp1).opcode Of
  6724. A_FMULP,A_FADDP,
  6725. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6726. begin
  6727. case taicpu(hp1).opcode Of
  6728. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6729. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6730. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6731. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6732. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6733. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6734. else
  6735. internalerror(2019050534);
  6736. end;
  6737. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6738. taicpu(hp1).oper[1]^.reg := NR_ST;
  6739. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6740. RemoveCurrentP(p, hp1);
  6741. Result:=true;
  6742. exit;
  6743. end;
  6744. else
  6745. ;
  6746. end;
  6747. end
  6748. else
  6749. if MatchOpType(taicpu(p),top_ref) and
  6750. GetNextInstruction(p, hp2) and
  6751. (hp2.typ = Ait_Instruction) and
  6752. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6753. (taicpu(p).opsize in [S_FS, S_FL]) and
  6754. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6755. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6756. if GetLastInstruction(p, hp1) and
  6757. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6758. MatchOpType(taicpu(hp1),top_ref) and
  6759. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6760. if ((taicpu(hp2).opcode = A_FMULP) or
  6761. (taicpu(hp2).opcode = A_FADDP)) then
  6762. { change to
  6763. fld/fst mem1 (hp1) fld/fst mem1
  6764. fld mem1 (p) fadd/
  6765. faddp/ fmul st, st
  6766. fmulp st, st1 (hp2) }
  6767. begin
  6768. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6769. RemoveCurrentP(p, hp1);
  6770. if (taicpu(hp2).opcode = A_FADDP) then
  6771. taicpu(hp2).opcode := A_FADD
  6772. else
  6773. taicpu(hp2).opcode := A_FMUL;
  6774. taicpu(hp2).oper[1]^.reg := NR_ST;
  6775. end
  6776. else
  6777. { change to
  6778. fld/fst mem1 (hp1) fld/fst mem1
  6779. fld mem1 (p) fld st
  6780. }
  6781. begin
  6782. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6783. taicpu(p).changeopsize(S_FL);
  6784. taicpu(p).loadreg(0,NR_ST);
  6785. end
  6786. else
  6787. begin
  6788. case taicpu(hp2).opcode Of
  6789. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6790. { change to
  6791. fld/fst mem1 (hp1) fld/fst mem1
  6792. fld mem2 (p) fxxx mem2
  6793. fxxxp st, st1 (hp2) }
  6794. begin
  6795. case taicpu(hp2).opcode Of
  6796. A_FADDP: taicpu(p).opcode := A_FADD;
  6797. A_FMULP: taicpu(p).opcode := A_FMUL;
  6798. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6799. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6800. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6801. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6802. else
  6803. internalerror(2019050533);
  6804. end;
  6805. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6806. RemoveInstruction(hp2);
  6807. end
  6808. else
  6809. ;
  6810. end
  6811. end
  6812. end;
  6813. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6814. begin
  6815. Result := condition_in(cond1, cond2) or
  6816. { Not strictly subsets due to the actual flags checked, but because we're
  6817. comparing integers, E is a subset of AE and GE and their aliases }
  6818. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6819. end;
  6820. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6821. var
  6822. v: TCGInt;
  6823. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6824. FirstMatch, TempBool: Boolean;
  6825. NewReg: TRegister;
  6826. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6827. begin
  6828. Result:=false;
  6829. { All these optimisations need a next instruction }
  6830. if not GetNextInstruction(p, hp1) then
  6831. Exit;
  6832. { Search for:
  6833. cmp ###,###
  6834. j(c1) @lbl1
  6835. ...
  6836. @lbl:
  6837. cmp ###,### (same comparison as above)
  6838. j(c2) @lbl2
  6839. If c1 is a subset of c2, change to:
  6840. cmp ###,###
  6841. j(c1) @lbl2
  6842. (@lbl1 may become a dead label as a result)
  6843. }
  6844. { Also handle cases where there are multiple jumps in a row }
  6845. p_jump := hp1;
  6846. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6847. begin
  6848. if IsJumpToLabel(taicpu(p_jump)) then
  6849. begin
  6850. { Do jump optimisations first in case the condition becomes
  6851. unnecessary }
  6852. TempBool := True;
  6853. if DoJumpOptimizations(p_jump, TempBool) or
  6854. not TempBool then
  6855. begin
  6856. if Assigned(p_jump) then
  6857. begin
  6858. hp1 := p_jump;
  6859. if (p_jump.typ in [ait_align]) then
  6860. SkipAligns(p_jump, p_jump);
  6861. { CollapseZeroDistJump will be set to the label after the
  6862. jump if it optimises, whether or not it's live or dead }
  6863. if (p_jump.typ in [ait_label]) and
  6864. not (tai_label(p_jump).labsym.is_used) then
  6865. GetNextInstruction(p_jump, p_jump);
  6866. end;
  6867. TransferUsedRegs(TmpUsedRegs);
  6868. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6869. if not Assigned(p_jump) or
  6870. (
  6871. not MatchInstruction(p_jump, A_Jcc, A_SETcc, A_CMOVcc, []) and
  6872. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_jump, TmpUsedRegs)
  6873. ) then
  6874. begin
  6875. { No more conditional jumps; conditional statement is no longer required }
  6876. DebugMsg(SPeepholeOptimization + 'Removed unnecessary condition (Cmp2Nop)', p);
  6877. RemoveCurrentP(p);
  6878. Result := True;
  6879. Exit;
  6880. end;
  6881. hp1 := p_jump;
  6882. Include(OptsToCheck, aoc_ForceNewIteration);
  6883. Continue;
  6884. end;
  6885. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6886. if GetNextInstruction(p_jump, hp2) and
  6887. (
  6888. OptimizeConditionalJump(JumpLabel, p_jump, hp2, TempBool) or
  6889. not TempBool
  6890. ) then
  6891. begin
  6892. hp1 := p_jump;
  6893. Include(OptsToCheck, aoc_ForceNewIteration);
  6894. Continue;
  6895. end;
  6896. p_label := nil;
  6897. if Assigned(JumpLabel) then
  6898. p_label := getlabelwithsym(JumpLabel);
  6899. if Assigned(p_label) and
  6900. GetNextInstruction(p_label, p_dist) and
  6901. MatchInstruction(p_dist, A_CMP, []) and
  6902. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6903. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6904. GetNextInstruction(p_dist, hp1_dist) and
  6905. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6906. begin
  6907. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6908. if JumpLabel = JumpLabel_dist then
  6909. { This is an infinite loop }
  6910. Exit;
  6911. { Best optimisation when the first condition is a subset (or equal) of the second }
  6912. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6913. begin
  6914. { Any registers used here will already be allocated }
  6915. if Assigned(JumpLabel) then
  6916. JumpLabel.DecRefs;
  6917. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6918. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  6919. Result := True;
  6920. { Don't exit yet. Since p and p_jump haven't actually been
  6921. removed, we can check for more on this iteration }
  6922. end
  6923. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6924. GetNextInstruction(hp1_dist, hp1_label) and
  6925. SkipAligns(hp1_label, hp1_label) and
  6926. (hp1_label.typ = ait_label) then
  6927. begin
  6928. JumpLabel_far := tai_label(hp1_label).labsym;
  6929. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6930. { This is an infinite loop }
  6931. Exit;
  6932. if Assigned(JumpLabel_far) then
  6933. begin
  6934. { In this situation, if the first jump branches, the second one will never,
  6935. branch so change the destination label to after the second jump }
  6936. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  6937. if Assigned(JumpLabel) then
  6938. JumpLabel.DecRefs;
  6939. JumpLabel_far.IncRefs;
  6940. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  6941. Result := True;
  6942. { Don't exit yet. Since p and p_jump haven't actually been
  6943. removed, we can check for more on this iteration }
  6944. Continue;
  6945. end;
  6946. end;
  6947. end;
  6948. end;
  6949. { Search for:
  6950. cmp ###,###
  6951. j(c1) @lbl1
  6952. cmp ###,### (same as first)
  6953. Remove second cmp
  6954. }
  6955. if GetNextInstruction(p_jump, hp2) and
  6956. (
  6957. (
  6958. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  6959. (
  6960. (
  6961. MatchOpType(taicpu(p), top_const, top_reg) and
  6962. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6963. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  6964. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6965. ) or (
  6966. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  6967. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  6968. )
  6969. )
  6970. ) or (
  6971. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6972. MatchOperand(taicpu(p).oper[0]^, 0) and
  6973. (taicpu(p).oper[1]^.typ = top_reg) and
  6974. MatchInstruction(hp2, A_TEST, []) and
  6975. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6976. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6977. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6978. )
  6979. ) then
  6980. begin
  6981. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6982. RemoveInstruction(hp2);
  6983. Result := True;
  6984. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6985. end;
  6986. GetNextInstruction(p_jump, p_jump);
  6987. end;
  6988. if (
  6989. { Don't call GetNextInstruction again if we already have it }
  6990. (hp1 = p_jump) or
  6991. GetNextInstruction(p, hp1)
  6992. ) and
  6993. MatchInstruction(hp1, A_Jcc, []) and
  6994. IsJumpToLabel(taicpu(hp1)) and
  6995. (taicpu(hp1).condition in [C_E, C_Z, C_NE, C_NZ]) and
  6996. GetNextInstruction(hp1, hp2) then
  6997. begin
  6998. {
  6999. cmp x, y (or "cmp y, x")
  7000. je @lbl
  7001. mov x, y
  7002. @lbl:
  7003. (x and y can be constants, registers or references)
  7004. Change to:
  7005. mov x, y (x and y will always be equal in the end)
  7006. @lbl: (may beceome a dead label)
  7007. Also:
  7008. cmp x, y (or "cmp y, x")
  7009. jne @lbl
  7010. mov x, y
  7011. @lbl:
  7012. (x and y can be constants, registers or references)
  7013. Change to:
  7014. Absolutely nothing! (Except @lbl if it's still live)
  7015. }
  7016. if MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  7017. (
  7018. (
  7019. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[0]^) and
  7020. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^)
  7021. ) or (
  7022. MatchOperand(taicpu(p).oper[0]^, taicpu(hp2).oper[1]^) and
  7023. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[0]^)
  7024. )
  7025. ) and
  7026. GetNextInstruction(hp2, hp1_label) and
  7027. SkipAligns(hp1_label, hp1_label) and
  7028. (hp1_label.typ = ait_label) and
  7029. (tai_label(hp1_label).labsym = taicpu(hp1).oper[0]^.ref^.symbol) then
  7030. begin
  7031. tai_label(hp1_label).labsym.DecRefs;
  7032. if (taicpu(hp1).condition in [C_NE, C_NZ]) then
  7033. begin
  7034. DebugMsg(SPeepholeOptimization + 'CMP/JNE/MOV/@Lbl -> NOP, since the MOV is only executed if the operands are equal (CmpJneMov2Nop)', p);
  7035. RemoveInstruction(hp2);
  7036. hp2 := hp1_label; { So RemoveCurrentp below can be set to something valid }
  7037. end
  7038. else
  7039. DebugMsg(SPeepholeOptimization + 'CMP/JE/MOV/@Lbl -> MOV, since the MOV is only executed if the operands aren''t equal (CmpJeMov2Mov)', p);
  7040. RemoveInstruction(hp1);
  7041. RemoveCurrentp(p, hp2);
  7042. Result := True;
  7043. Exit;
  7044. end;
  7045. {
  7046. Try to optimise the following:
  7047. cmp $x,### ($x and $y can be registers or constants)
  7048. je @lbl1 (only reference)
  7049. cmp $y,### (### are identical)
  7050. @Lbl:
  7051. sete %reg1
  7052. Change to:
  7053. cmp $x,###
  7054. sete %reg2 (allocate new %reg2)
  7055. cmp $y,###
  7056. sete %reg1
  7057. orb %reg2,%reg1
  7058. (dealloc %reg2)
  7059. This adds an instruction (so don't perform under -Os), but it removes
  7060. a conditional branch.
  7061. }
  7062. if not (cs_opt_size in current_settings.optimizerswitches) and
  7063. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  7064. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  7065. { The first operand of CMP instructions can only be a register or
  7066. immediate anyway, so no need to check }
  7067. GetNextInstruction(hp2, p_label) and
  7068. (p_label.typ = ait_label) and
  7069. (tai_label(p_label).labsym.getrefs = 1) and
  7070. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  7071. GetNextInstruction(p_label, p_dist) and
  7072. MatchInstruction(p_dist, A_SETcc, []) and
  7073. (taicpu(p_dist).condition in [C_E, C_Z]) and
  7074. (taicpu(p_dist).oper[0]^.typ = top_reg) then
  7075. begin
  7076. TransferUsedRegs(TmpUsedRegs);
  7077. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7078. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7079. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  7080. UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  7081. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  7082. { Get the instruction after the SETcc instruction so we can
  7083. allocate a new register over the entire range }
  7084. GetNextInstruction(p_dist, hp1_dist) then
  7085. begin
  7086. { Register can appear in p if it's not used afterwards, so only
  7087. allocate between hp1 and hp1_dist }
  7088. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, hp1_dist);
  7089. if NewReg <> NR_NO then
  7090. begin
  7091. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  7092. { Change the jump instruction into a SETcc instruction }
  7093. taicpu(hp1).opcode := A_SETcc;
  7094. taicpu(hp1).opsize := S_B;
  7095. taicpu(hp1).loadreg(0, NewReg);
  7096. { This is now a dead label }
  7097. tai_label(p_label).labsym.decrefs;
  7098. { Prefer adding before the next instruction so the FLAGS
  7099. register is deallicated first }
  7100. AsmL.InsertBefore(
  7101. taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg),
  7102. hp1_dist
  7103. );
  7104. Result := True;
  7105. { Don't exit yet, as p wasn't changed and hp1, while
  7106. modified, is still intact and might be optimised by the
  7107. SETcc optimisation below }
  7108. end;
  7109. end;
  7110. end;
  7111. end;
  7112. if taicpu(p).oper[0]^.typ = top_const then
  7113. begin
  7114. if (taicpu(p).oper[0]^.val = 0) and
  7115. (taicpu(p).oper[1]^.typ = top_reg) and
  7116. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  7117. begin
  7118. hp2 := p;
  7119. FirstMatch := True;
  7120. { When dealing with "cmp $0,%reg", only ZF and SF contain
  7121. anything meaningful once it's converted to "test %reg,%reg";
  7122. additionally, some jumps will always (or never) branch, so
  7123. evaluate every jump immediately following the
  7124. comparison, optimising the conditions if possible.
  7125. Similarly with SETcc... those that are always set to 0 or 1
  7126. are changed to MOV instructions }
  7127. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  7128. (
  7129. GetNextInstruction(hp2, hp1) and
  7130. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  7131. ) do
  7132. begin
  7133. FirstMatch := False;
  7134. case taicpu(hp1).condition of
  7135. C_B, C_C, C_NAE, C_O:
  7136. { For B/NAE:
  7137. Will never branch since an unsigned integer can never be below zero
  7138. For C/O:
  7139. Result cannot overflow because 0 is being subtracted
  7140. }
  7141. begin
  7142. if taicpu(hp1).opcode = A_Jcc then
  7143. begin
  7144. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  7145. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  7146. RemoveInstruction(hp1);
  7147. { Since hp1 was deleted, hp2 must not be updated }
  7148. Continue;
  7149. end
  7150. else
  7151. begin
  7152. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  7153. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  7154. taicpu(hp1).opcode := A_MOV;
  7155. taicpu(hp1).ops := 2;
  7156. taicpu(hp1).condition := C_None;
  7157. taicpu(hp1).opsize := S_B;
  7158. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7159. taicpu(hp1).loadconst(0, 0);
  7160. end;
  7161. end;
  7162. C_BE, C_NA:
  7163. begin
  7164. { Will only branch if equal to zero }
  7165. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  7166. taicpu(hp1).condition := C_E;
  7167. end;
  7168. C_A, C_NBE:
  7169. begin
  7170. { Will only branch if not equal to zero }
  7171. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  7172. taicpu(hp1).condition := C_NE;
  7173. end;
  7174. C_AE, C_NB, C_NC, C_NO:
  7175. begin
  7176. { Will always branch }
  7177. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  7178. if taicpu(hp1).opcode = A_Jcc then
  7179. begin
  7180. MakeUnconditional(taicpu(hp1));
  7181. { Any jumps/set that follow will now be dead code }
  7182. RemoveDeadCodeAfterJump(taicpu(hp1));
  7183. Break;
  7184. end
  7185. else
  7186. begin
  7187. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  7188. taicpu(hp1).opcode := A_MOV;
  7189. taicpu(hp1).ops := 2;
  7190. taicpu(hp1).condition := C_None;
  7191. taicpu(hp1).opsize := S_B;
  7192. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  7193. taicpu(hp1).loadconst(0, 1);
  7194. end;
  7195. end;
  7196. C_None:
  7197. InternalError(2020012201);
  7198. C_P, C_PE, C_NP, C_PO:
  7199. { We can't handle parity checks and they should never be generated
  7200. after a general-purpose CMP (it's used in some floating-point
  7201. comparisons that don't use CMP) }
  7202. InternalError(2020012202);
  7203. else
  7204. { Zero/Equality, Sign, their complements and all of the
  7205. signed comparisons do not need to be converted };
  7206. end;
  7207. hp2 := hp1;
  7208. end;
  7209. { Convert the instruction to a TEST }
  7210. taicpu(p).opcode := A_TEST;
  7211. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7212. Result := True;
  7213. Exit;
  7214. end
  7215. else if (taicpu(p).oper[0]^.val = 1) and
  7216. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7217. (taicpu(hp1).condition in [C_L, C_NL, C_NGE, C_GE]) then
  7218. begin
  7219. { Convert; To:
  7220. cmp $1,r/m cmp $0,r/m
  7221. jl @lbl jle @lbl
  7222. (Also do inverted conditions)
  7223. }
  7224. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  7225. taicpu(p).oper[0]^.val := 0;
  7226. if taicpu(hp1).condition in [C_L, C_NGE] then
  7227. taicpu(hp1).condition := C_LE
  7228. else
  7229. taicpu(hp1).condition := C_NLE;
  7230. { If the instruction is now "cmp $0,%reg", convert it to a
  7231. TEST (and effectively do the work of the "cmp $0,%reg" in
  7232. the block above)
  7233. }
  7234. if (taicpu(p).oper[1]^.typ = top_reg) then
  7235. begin
  7236. taicpu(p).opcode := A_TEST;
  7237. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  7238. end;
  7239. Result := True;
  7240. Exit;
  7241. end
  7242. else if (taicpu(p).oper[1]^.typ = top_reg)
  7243. {$ifdef x86_64}
  7244. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  7245. {$endif x86_64}
  7246. then
  7247. begin
  7248. { cmp register,$8000 neg register
  7249. je target --> jo target
  7250. .... only if register is deallocated before jump.}
  7251. case Taicpu(p).opsize of
  7252. S_B: v:=$80;
  7253. S_W: v:=$8000;
  7254. S_L: v:=qword($80000000);
  7255. else
  7256. internalerror(2013112905);
  7257. end;
  7258. if (taicpu(p).oper[0]^.val=v) and
  7259. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  7260. (Taicpu(hp1).condition in [C_E,C_NE]) then
  7261. begin
  7262. TransferUsedRegs(TmpUsedRegs);
  7263. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  7264. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  7265. begin
  7266. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  7267. Taicpu(p).opcode:=A_NEG;
  7268. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  7269. Taicpu(p).clearop(1);
  7270. Taicpu(p).ops:=1;
  7271. if Taicpu(hp1).condition=C_E then
  7272. Taicpu(hp1).condition:=C_O
  7273. else
  7274. Taicpu(hp1).condition:=C_NO;
  7275. Result:=true;
  7276. exit;
  7277. end;
  7278. end;
  7279. end;
  7280. end;
  7281. if TrySwapMovCmp(p, hp1) then
  7282. begin
  7283. Result := True;
  7284. Exit;
  7285. end;
  7286. end;
  7287. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  7288. var
  7289. hp1: tai;
  7290. begin
  7291. {
  7292. remove the second (v)pxor from
  7293. pxor reg,reg
  7294. ...
  7295. pxor reg,reg
  7296. }
  7297. Result:=false;
  7298. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7299. MatchOpType(taicpu(p),top_reg,top_reg) and
  7300. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7301. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7302. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7303. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7304. begin
  7305. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7306. RemoveInstruction(hp1);
  7307. Result:=true;
  7308. Exit;
  7309. end
  7310. {
  7311. replace
  7312. pxor reg1,reg1
  7313. movapd/s reg1,reg2
  7314. dealloc reg1
  7315. by
  7316. pxor reg2,reg2
  7317. }
  7318. else if GetNextInstruction(p,hp1) and
  7319. { we mix single and double opperations here because we assume that the compiler
  7320. generates vmovapd only after double operations and vmovaps only after single operations }
  7321. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7322. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7323. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7324. (taicpu(p).oper[0]^.typ=top_reg) then
  7325. begin
  7326. TransferUsedRegs(TmpUsedRegs);
  7327. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7328. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7329. begin
  7330. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7331. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7332. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7333. RemoveInstruction(hp1);
  7334. result:=true;
  7335. end;
  7336. end;
  7337. end;
  7338. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7339. var
  7340. hp1: tai;
  7341. begin
  7342. {
  7343. remove the second (v)pxor from
  7344. (v)pxor reg,reg
  7345. ...
  7346. (v)pxor reg,reg
  7347. }
  7348. Result:=false;
  7349. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7350. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7351. begin
  7352. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7353. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7354. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7355. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7356. begin
  7357. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7358. RemoveInstruction(hp1);
  7359. Result:=true;
  7360. Exit;
  7361. end;
  7362. {$ifdef x86_64}
  7363. {
  7364. replace
  7365. vpxor reg1,reg1,reg1
  7366. vmov reg,mem
  7367. by
  7368. movq $0,mem
  7369. }
  7370. if GetNextInstruction(p,hp1) and
  7371. MatchInstruction(hp1,A_VMOVSD,[]) and
  7372. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7373. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7374. begin
  7375. TransferUsedRegs(TmpUsedRegs);
  7376. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7377. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7378. begin
  7379. taicpu(hp1).loadconst(0,0);
  7380. taicpu(hp1).opcode:=A_MOV;
  7381. taicpu(hp1).opsize:=S_Q;
  7382. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7383. RemoveCurrentP(p);
  7384. result:=true;
  7385. Exit;
  7386. end;
  7387. end;
  7388. {$endif x86_64}
  7389. end
  7390. {
  7391. replace
  7392. vpxor reg1,reg1,reg2
  7393. by
  7394. vpxor reg2,reg2,reg2
  7395. to avoid unncessary data dependencies
  7396. }
  7397. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7398. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7399. begin
  7400. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7401. { avoid unncessary data dependency }
  7402. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7403. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7404. result:=true;
  7405. exit;
  7406. end;
  7407. Result:=OptPass1VOP(p);
  7408. end;
  7409. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7410. var
  7411. hp1 : tai;
  7412. begin
  7413. result:=false;
  7414. { replace
  7415. IMul const,%mreg1,%mreg2
  7416. Mov %reg2,%mreg3
  7417. dealloc %mreg3
  7418. by
  7419. Imul const,%mreg1,%mreg23
  7420. }
  7421. if (taicpu(p).ops=3) and
  7422. GetNextInstruction(p,hp1) and
  7423. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7424. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7425. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7426. begin
  7427. TransferUsedRegs(TmpUsedRegs);
  7428. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7429. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7430. begin
  7431. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7432. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7433. RemoveInstruction(hp1);
  7434. result:=true;
  7435. end;
  7436. end;
  7437. end;
  7438. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7439. var
  7440. hp1 : tai;
  7441. begin
  7442. result:=false;
  7443. { replace
  7444. IMul %reg0,%reg1,%reg2
  7445. Mov %reg2,%reg3
  7446. dealloc %reg2
  7447. by
  7448. Imul %reg0,%reg1,%reg3
  7449. }
  7450. if GetNextInstruction(p,hp1) and
  7451. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7452. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7453. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7454. begin
  7455. TransferUsedRegs(TmpUsedRegs);
  7456. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7457. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7458. begin
  7459. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7460. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7461. RemoveInstruction(hp1);
  7462. result:=true;
  7463. end;
  7464. end;
  7465. end;
  7466. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7467. var
  7468. hp1: tai;
  7469. begin
  7470. Result:=false;
  7471. { get rid of
  7472. (v)cvtss2sd reg0,<reg1,>reg2
  7473. (v)cvtss2sd reg2,<reg2,>reg0
  7474. }
  7475. if GetNextInstruction(p,hp1) and
  7476. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7477. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7478. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7479. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7480. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7481. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7482. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7483. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7484. )
  7485. ) then
  7486. begin
  7487. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7488. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7489. begin
  7490. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7491. RemoveCurrentP(p);
  7492. RemoveInstruction(hp1);
  7493. end
  7494. else
  7495. begin
  7496. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7497. if taicpu(hp1).opcode=A_CVTSD2SS then
  7498. begin
  7499. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7500. taicpu(p).opcode:=A_MOVAPS;
  7501. end
  7502. else
  7503. begin
  7504. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7505. taicpu(p).opcode:=A_VMOVAPS;
  7506. end;
  7507. taicpu(p).ops:=2;
  7508. RemoveInstruction(hp1);
  7509. end;
  7510. Result:=true;
  7511. Exit;
  7512. end;
  7513. end;
  7514. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7515. var
  7516. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7517. ThisReg: TRegister;
  7518. begin
  7519. Result := False;
  7520. if not GetNextInstruction(p,hp1) then
  7521. Exit;
  7522. {
  7523. convert
  7524. j<c> .L1
  7525. mov 1,reg
  7526. jmp .L2
  7527. .L1
  7528. mov 0,reg
  7529. .L2
  7530. into
  7531. mov 0,reg
  7532. set<not(c)> reg
  7533. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7534. would destroy the flag contents
  7535. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7536. executed at the same time as a previous comparison.
  7537. set<not(c)> reg
  7538. movzx reg, reg
  7539. }
  7540. if MatchInstruction(hp1,A_MOV,[]) and
  7541. (taicpu(hp1).oper[0]^.typ = top_const) and
  7542. (
  7543. (
  7544. (taicpu(hp1).oper[1]^.typ = top_reg)
  7545. {$ifdef i386}
  7546. { Under i386, ESI, EDI, EBP and ESP
  7547. don't have an 8-bit representation }
  7548. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7549. {$endif i386}
  7550. ) or (
  7551. {$ifdef i386}
  7552. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7553. {$endif i386}
  7554. (taicpu(hp1).opsize = S_B)
  7555. )
  7556. ) and
  7557. GetNextInstruction(hp1,hp2) and
  7558. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7559. GetNextInstruction(hp2,hp3) and
  7560. SkipAligns(hp3, hp3) and
  7561. (hp3.typ=ait_label) and
  7562. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7563. GetNextInstruction(hp3,hp4) and
  7564. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7565. (taicpu(hp4).oper[0]^.typ = top_const) and
  7566. (
  7567. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7568. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7569. ) and
  7570. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7571. GetNextInstruction(hp4,hp5) and
  7572. SkipAligns(hp5, hp5) and
  7573. (hp5.typ=ait_label) and
  7574. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7575. begin
  7576. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7577. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7578. tai_label(hp3).labsym.DecRefs;
  7579. { If this isn't the only reference to the middle label, we can
  7580. still make a saving - only that the first jump and everything
  7581. that follows will remain. }
  7582. if (tai_label(hp3).labsym.getrefs = 0) then
  7583. begin
  7584. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7585. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7586. else
  7587. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7588. { remove jump, first label and second MOV (also catching any aligns) }
  7589. repeat
  7590. if not GetNextInstruction(hp2, hp3) then
  7591. InternalError(2021040810);
  7592. RemoveInstruction(hp2);
  7593. hp2 := hp3;
  7594. until hp2 = hp5;
  7595. { Don't decrement reference count before the removal loop
  7596. above, otherwise GetNextInstruction won't stop on the
  7597. the label }
  7598. tai_label(hp5).labsym.DecRefs;
  7599. end
  7600. else
  7601. begin
  7602. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7603. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7604. else
  7605. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7606. end;
  7607. taicpu(p).opcode:=A_SETcc;
  7608. taicpu(p).opsize:=S_B;
  7609. taicpu(p).is_jmp:=False;
  7610. if taicpu(hp1).opsize=S_B then
  7611. begin
  7612. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7613. if taicpu(hp1).oper[1]^.typ = top_reg then
  7614. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7615. RemoveInstruction(hp1);
  7616. end
  7617. else
  7618. begin
  7619. { Will be a register because the size can't be S_B otherwise }
  7620. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7621. taicpu(p).loadreg(0, ThisReg);
  7622. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7623. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7624. begin
  7625. case taicpu(hp1).opsize of
  7626. S_W:
  7627. taicpu(hp1).opsize := S_BW;
  7628. S_L:
  7629. taicpu(hp1).opsize := S_BL;
  7630. {$ifdef x86_64}
  7631. S_Q:
  7632. begin
  7633. taicpu(hp1).opsize := S_BL;
  7634. { Change the destination register to 32-bit }
  7635. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7636. end;
  7637. {$endif x86_64}
  7638. else
  7639. InternalError(2021040820);
  7640. end;
  7641. taicpu(hp1).opcode := A_MOVZX;
  7642. taicpu(hp1).loadreg(0, ThisReg);
  7643. end
  7644. else
  7645. begin
  7646. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7647. { hp1 is already a MOV instruction with the correct register }
  7648. taicpu(hp1).loadconst(0, 0);
  7649. { Inserting it right before p will guarantee that the flags are also tracked }
  7650. asml.Remove(hp1);
  7651. asml.InsertBefore(hp1, p);
  7652. end;
  7653. end;
  7654. Result:=true;
  7655. exit;
  7656. end
  7657. else if (hp1.typ = ait_label) then
  7658. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7659. end;
  7660. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7661. var
  7662. hp1, hp2, hp3: tai;
  7663. SourceRef, TargetRef: TReference;
  7664. CurrentReg: TRegister;
  7665. begin
  7666. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7667. if not UseAVX then
  7668. InternalError(2021100501);
  7669. Result := False;
  7670. { Look for the following to simplify:
  7671. vmovdqa/u x(mem1), %xmmreg
  7672. vmovdqa/u %xmmreg, y(mem2)
  7673. vmovdqa/u x+16(mem1), %xmmreg
  7674. vmovdqa/u %xmmreg, y+16(mem2)
  7675. Change to:
  7676. vmovdqa/u x(mem1), %ymmreg
  7677. vmovdqa/u %ymmreg, y(mem2)
  7678. vpxor %ymmreg, %ymmreg, %ymmreg
  7679. ( The VPXOR instruction is to zero the upper half, thus removing the
  7680. need to call the potentially expensive VZEROUPPER instruction. Other
  7681. peephole optimisations can remove VPXOR if it's unnecessary )
  7682. }
  7683. TransferUsedRegs(TmpUsedRegs);
  7684. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7685. { NOTE: In the optimisations below, if the references dictate that an
  7686. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7687. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7688. if (taicpu(p).opsize = S_XMM) and
  7689. MatchOpType(taicpu(p), top_ref, top_reg) and
  7690. GetNextInstruction(p, hp1) and
  7691. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7692. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7693. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7694. begin
  7695. SourceRef := taicpu(p).oper[0]^.ref^;
  7696. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7697. if GetNextInstruction(hp1, hp2) and
  7698. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7699. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7700. begin
  7701. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7702. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7703. Inc(SourceRef.offset, 16);
  7704. { Reuse the register in the first block move }
  7705. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7706. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7707. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7708. begin
  7709. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7710. Inc(TargetRef.offset, 16);
  7711. if GetNextInstruction(hp2, hp3) and
  7712. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7713. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7714. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7715. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7716. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7717. begin
  7718. { Update the register tracking to the new size }
  7719. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7720. { Remember that the offsets are 16 ahead }
  7721. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7722. if not (
  7723. ((SourceRef.offset mod 32) = 16) and
  7724. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7725. ) then
  7726. taicpu(p).opcode := A_VMOVDQU;
  7727. taicpu(p).opsize := S_YMM;
  7728. taicpu(p).oper[1]^.reg := CurrentReg;
  7729. if not (
  7730. ((TargetRef.offset mod 32) = 16) and
  7731. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7732. ) then
  7733. taicpu(hp1).opcode := A_VMOVDQU;
  7734. taicpu(hp1).opsize := S_YMM;
  7735. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7736. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7737. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7738. if (pi_uses_ymm in current_procinfo.flags) then
  7739. RemoveInstruction(hp2)
  7740. else
  7741. begin
  7742. taicpu(hp2).opcode := A_VPXOR;
  7743. taicpu(hp2).opsize := S_YMM;
  7744. taicpu(hp2).loadreg(0, CurrentReg);
  7745. taicpu(hp2).loadreg(1, CurrentReg);
  7746. taicpu(hp2).loadreg(2, CurrentReg);
  7747. taicpu(hp2).ops := 3;
  7748. end;
  7749. RemoveInstruction(hp3);
  7750. Result := True;
  7751. Exit;
  7752. end;
  7753. end
  7754. else
  7755. begin
  7756. { See if the next references are 16 less rather than 16 greater }
  7757. Dec(SourceRef.offset, 32); { -16 the other way }
  7758. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7759. begin
  7760. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7761. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7762. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7763. GetNextInstruction(hp2, hp3) and
  7764. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7765. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7766. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7767. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7768. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7769. begin
  7770. { Update the register tracking to the new size }
  7771. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7772. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7773. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7774. if not(
  7775. ((SourceRef.offset mod 32) = 0) and
  7776. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7777. ) then
  7778. taicpu(hp2).opcode := A_VMOVDQU;
  7779. taicpu(hp2).opsize := S_YMM;
  7780. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7781. if not (
  7782. ((TargetRef.offset mod 32) = 0) and
  7783. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7784. ) then
  7785. taicpu(hp3).opcode := A_VMOVDQU;
  7786. taicpu(hp3).opsize := S_YMM;
  7787. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7788. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7789. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7790. if (pi_uses_ymm in current_procinfo.flags) then
  7791. RemoveInstruction(hp1)
  7792. else
  7793. begin
  7794. taicpu(hp1).opcode := A_VPXOR;
  7795. taicpu(hp1).opsize := S_YMM;
  7796. taicpu(hp1).loadreg(0, CurrentReg);
  7797. taicpu(hp1).loadreg(1, CurrentReg);
  7798. taicpu(hp1).loadreg(2, CurrentReg);
  7799. taicpu(hp1).ops := 3;
  7800. Asml.Remove(hp1);
  7801. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7802. end;
  7803. RemoveCurrentP(p, hp2);
  7804. Result := True;
  7805. Exit;
  7806. end;
  7807. end;
  7808. end;
  7809. end;
  7810. end;
  7811. end;
  7812. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7813. var
  7814. hp2, hp3, first_assignment: tai;
  7815. IncCount, OperIdx: Integer;
  7816. OrigLabel: TAsmLabel;
  7817. begin
  7818. Count := 0;
  7819. Result := False;
  7820. first_assignment := nil;
  7821. if (LoopCount >= 20) then
  7822. begin
  7823. { Guard against infinite loops }
  7824. Exit;
  7825. end;
  7826. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7827. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7828. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7829. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7830. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7831. Exit;
  7832. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7833. {
  7834. change
  7835. jmp .L1
  7836. ...
  7837. .L1:
  7838. mov ##, ## ( multiple movs possible )
  7839. jmp/ret
  7840. into
  7841. mov ##, ##
  7842. jmp/ret
  7843. }
  7844. if not Assigned(hp1) then
  7845. begin
  7846. hp1 := GetLabelWithSym(OrigLabel);
  7847. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7848. Exit;
  7849. end;
  7850. hp2 := hp1;
  7851. while Assigned(hp2) do
  7852. begin
  7853. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7854. SkipLabels(hp2,hp2);
  7855. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7856. Break;
  7857. case taicpu(hp2).opcode of
  7858. A_MOVSD:
  7859. begin
  7860. if taicpu(hp2).ops = 0 then
  7861. { Wrong MOVSD }
  7862. Break;
  7863. Inc(Count);
  7864. if Count >= 5 then
  7865. { Too many to be worthwhile }
  7866. Break;
  7867. GetNextInstruction(hp2, hp2);
  7868. Continue;
  7869. end;
  7870. A_MOV,
  7871. A_MOVD,
  7872. A_MOVQ,
  7873. A_MOVSX,
  7874. {$ifdef x86_64}
  7875. A_MOVSXD,
  7876. {$endif x86_64}
  7877. A_MOVZX,
  7878. A_MOVAPS,
  7879. A_MOVUPS,
  7880. A_MOVSS,
  7881. A_MOVAPD,
  7882. A_MOVUPD,
  7883. A_MOVDQA,
  7884. A_MOVDQU,
  7885. A_VMOVSS,
  7886. A_VMOVAPS,
  7887. A_VMOVUPS,
  7888. A_VMOVSD,
  7889. A_VMOVAPD,
  7890. A_VMOVUPD,
  7891. A_VMOVDQA,
  7892. A_VMOVDQU:
  7893. begin
  7894. Inc(Count);
  7895. if Count >= 5 then
  7896. { Too many to be worthwhile }
  7897. Break;
  7898. GetNextInstruction(hp2, hp2);
  7899. Continue;
  7900. end;
  7901. A_JMP:
  7902. begin
  7903. { Guard against infinite loops }
  7904. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7905. Exit;
  7906. { Analyse this jump first in case it also duplicates assignments }
  7907. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7908. begin
  7909. { Something did change! }
  7910. Result := True;
  7911. Inc(Count, IncCount);
  7912. if Count >= 5 then
  7913. begin
  7914. { Too many to be worthwhile }
  7915. Exit;
  7916. end;
  7917. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7918. Break;
  7919. end;
  7920. Result := True;
  7921. Break;
  7922. end;
  7923. A_RET:
  7924. begin
  7925. Result := True;
  7926. Break;
  7927. end;
  7928. else
  7929. Break;
  7930. end;
  7931. end;
  7932. if Result then
  7933. begin
  7934. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  7935. if Count = 0 then
  7936. begin
  7937. Result := False;
  7938. Exit;
  7939. end;
  7940. hp3 := p;
  7941. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  7942. while True do
  7943. begin
  7944. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  7945. SkipLabels(hp1,hp1);
  7946. if (hp1.typ <> ait_instruction) then
  7947. InternalError(2021040720);
  7948. case taicpu(hp1).opcode of
  7949. A_JMP:
  7950. begin
  7951. { Change the original jump to the new destination }
  7952. OrigLabel.decrefs;
  7953. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  7954. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  7955. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7956. if not Assigned(first_assignment) then
  7957. InternalError(2021040810)
  7958. else
  7959. p := first_assignment;
  7960. Exit;
  7961. end;
  7962. A_RET:
  7963. begin
  7964. { Now change the jump into a RET instruction }
  7965. ConvertJumpToRET(p, hp1);
  7966. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7967. if not Assigned(first_assignment) then
  7968. InternalError(2021040811)
  7969. else
  7970. p := first_assignment;
  7971. Exit;
  7972. end;
  7973. else
  7974. begin
  7975. { Duplicate the MOV instruction }
  7976. hp3:=tai(hp1.getcopy);
  7977. if first_assignment = nil then
  7978. first_assignment := hp3;
  7979. asml.InsertBefore(hp3, p);
  7980. { Make sure the compiler knows about any final registers written here }
  7981. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  7982. with taicpu(hp3).oper[OperIdx]^ do
  7983. begin
  7984. case typ of
  7985. top_ref:
  7986. begin
  7987. if (ref^.base <> NR_NO) and
  7988. (getsupreg(ref^.base) <> RS_ESP) and
  7989. (getsupreg(ref^.base) <> RS_EBP)
  7990. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  7991. then
  7992. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  7993. if (ref^.index <> NR_NO) and
  7994. (getsupreg(ref^.index) <> RS_ESP) and
  7995. (getsupreg(ref^.index) <> RS_EBP)
  7996. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  7997. (ref^.index <> ref^.base) then
  7998. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  7999. end;
  8000. top_reg:
  8001. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  8002. else
  8003. ;
  8004. end;
  8005. end;
  8006. end;
  8007. end;
  8008. if not GetNextInstruction(hp1, hp1) then
  8009. { Should have dropped out earlier }
  8010. InternalError(2021040710);
  8011. end;
  8012. end;
  8013. end;
  8014. const
  8015. WriteOp: array[0..3] of set of TInsChange = (
  8016. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  8017. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  8018. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  8019. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  8020. RegWriteFlags: array[0..7] of set of TInsChange = (
  8021. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  8022. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  8023. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  8024. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  8025. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  8026. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  8027. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  8028. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  8029. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  8030. function TX86AsmOptimizer.TrySwapMovOp(var p, hp1: tai): Boolean;
  8031. var
  8032. hp2: tai;
  8033. X: Integer;
  8034. begin
  8035. { If we have something like:
  8036. op ###,###
  8037. mov ###,###
  8038. Try to move the MOV instruction to before OP as long as OP and MOV don't
  8039. interfere in regards to what they write to.
  8040. NOTE: p must be a 2-operand instruction
  8041. }
  8042. Result := False;
  8043. if (hp1.typ <> ait_instruction) or
  8044. taicpu(hp1).is_jmp or
  8045. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  8046. Exit;
  8047. { NOP is a pipeline fence, likely marking the beginning of the function
  8048. epilogue, so drop out. Similarly, drop out if POP or RET are
  8049. encountered }
  8050. if MatchInstruction(hp1, A_NOP, A_POP, A_RET, []) then
  8051. Exit;
  8052. if (taicpu(hp1).opcode = A_MOVSD) and
  8053. (taicpu(hp1).ops = 0) then
  8054. { Wrong MOVSD }
  8055. Exit;
  8056. { Check for writes to specific registers first }
  8057. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8058. for X := 0 to 7 do
  8059. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  8060. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  8061. Exit;
  8062. for X := 0 to taicpu(hp1).ops - 1 do
  8063. begin
  8064. { Check to see if this operand writes to something }
  8065. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  8066. { And matches something in the CMP/TEST instruction }
  8067. (
  8068. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  8069. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  8070. (
  8071. { If it's a register, make sure the register written to doesn't
  8072. appear in the cmp instruction as part of a reference }
  8073. (taicpu(hp1).oper[X]^.typ = top_reg) and
  8074. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  8075. )
  8076. ) then
  8077. Exit;
  8078. end;
  8079. { Check p to make sure it doesn't write to something that affects hp1 }
  8080. { Check for writes to specific registers first }
  8081. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  8082. for X := 0 to 7 do
  8083. if (RegWriteFlags[X] * InsProp[taicpu(p).opcode].Ch <> [])
  8084. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), hp1) then
  8085. Exit;
  8086. for X := 0 to taicpu(p).ops - 1 do
  8087. begin
  8088. { Check to see if this operand writes to something }
  8089. if ((WriteOp[X] * InsProp[taicpu(p).opcode].Ch) <> []) and
  8090. { And matches something in hp1 }
  8091. (taicpu(p).oper[X]^.typ = top_reg) and
  8092. RegInInstruction(taicpu(p).oper[X]^.reg, hp1) then
  8093. Exit;
  8094. end;
  8095. { The instruction can be safely moved }
  8096. asml.Remove(hp1);
  8097. { Try to insert after the last instructions where the FLAGS register is not
  8098. yet in use, so "mov $0,%reg" can be optimised into "xor %reg,%reg" later }
  8099. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  8100. asml.InsertBefore(hp1, hp2)
  8101. { Failing that, try to insert after the last instructions where the
  8102. FLAGS register is not yet in use }
  8103. else if GetLastInstruction(p, hp2) and
  8104. (
  8105. (hp2.typ <> ait_instruction) or
  8106. { Don't insert after an instruction that uses the flags when p doesn't use them }
  8107. RegInInstruction(NR_DEFAULTFLAGS, p) or
  8108. not RegInInstruction(NR_DEFAULTFLAGS, hp2)
  8109. ) then
  8110. asml.InsertAfter(hp1, hp2)
  8111. else
  8112. { Note, if p.Previous is nil (even if it should logically never be the
  8113. case), FindRegAllocBackward immediately exits with False and so we
  8114. safely land here (we can't just pass p because FindRegAllocBackward
  8115. immediately exits on an instruction). [Kit] }
  8116. asml.InsertBefore(hp1, p);
  8117. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  8118. { We can't trust UsedRegs because we're looking backwards, although we
  8119. know the registers are allocated after p at the very least, so manually
  8120. create tai_regalloc objects if needed }
  8121. for X := 0 to taicpu(hp1).ops - 1 do
  8122. case taicpu(hp1).oper[X]^.typ of
  8123. top_reg:
  8124. begin
  8125. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.reg, nil), hp1);
  8126. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.reg, UsedRegs);
  8127. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  8128. end;
  8129. top_ref:
  8130. begin
  8131. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  8132. begin
  8133. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.base, nil), hp1);
  8134. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.base, UsedRegs);
  8135. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  8136. end;
  8137. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  8138. begin
  8139. asml.InsertBefore(tai_regalloc.alloc(taicpu(hp1).oper[X]^.ref^.index, nil), hp1);
  8140. IncludeRegInUsedRegs(taicpu(hp1).oper[X]^.ref^.index, UsedRegs);
  8141. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  8142. end;
  8143. end;
  8144. else
  8145. ;
  8146. end;
  8147. Result := True;
  8148. end;
  8149. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  8150. var
  8151. hp2: tai;
  8152. X: Integer;
  8153. begin
  8154. { If we have something like:
  8155. cmp ###,%reg1
  8156. mov 0,%reg2
  8157. And no modified registers are shared, move the instruction to before
  8158. the comparison as this means it can be optimised without worrying
  8159. about the FLAGS register. (CMP/MOV is generated by
  8160. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  8161. As long as the second instruction doesn't use the flags or one of the
  8162. registers used by CMP or TEST (also check any references that use the
  8163. registers), then it can be moved prior to the comparison.
  8164. }
  8165. Result := False;
  8166. if not TrySwapMovOp(p, hp1) then
  8167. Exit;
  8168. if taicpu(hp1).opcode = A_LEA then
  8169. { The flags will be overwritten by the CMP/TEST instruction }
  8170. ConvertLEA(taicpu(hp1));
  8171. Result := True;
  8172. { Can we move it one further back? }
  8173. if GetLastInstruction(hp1, hp2) and (hp2.typ = ait_instruction) and
  8174. { Check to see if CMP/TEST is a comparison against zero }
  8175. (
  8176. (
  8177. (taicpu(p).opcode = A_CMP) and
  8178. MatchOperand(taicpu(p).oper[0]^, 0)
  8179. ) or
  8180. (
  8181. (taicpu(p).opcode = A_TEST) and
  8182. (
  8183. OpsEqual(taicpu(p).oper[0]^, taicpu(p).oper[1]^) or
  8184. MatchOperand(taicpu(p).oper[0]^, -1)
  8185. )
  8186. )
  8187. ) and
  8188. { These instructions set the zero flag if the result is zero }
  8189. MatchInstruction(hp2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) and
  8190. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^) then
  8191. { Looks like we can - if successful, this benefits PostPeepholeOptTestOr }
  8192. TrySwapMovOp(hp2, hp1);
  8193. end;
  8194. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  8195. function IsXCHGAcceptable: Boolean; inline;
  8196. begin
  8197. { Always accept if optimising for size }
  8198. Result := (cs_opt_size in current_settings.optimizerswitches) or
  8199. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  8200. than 3, so it becomes a saving compared to three MOVs with two of
  8201. them able to execute simultaneously. [Kit] }
  8202. (CPUX86_HINT_FAST_XCHG in cpu_optimization_hints[current_settings.optimizecputype]);
  8203. end;
  8204. var
  8205. NewRef: TReference;
  8206. hp1, hp2, hp3, hp4: Tai;
  8207. {$ifndef x86_64}
  8208. OperIdx: Integer;
  8209. {$endif x86_64}
  8210. NewInstr : Taicpu;
  8211. NewAligh : Tai_align;
  8212. DestLabel: TAsmLabel;
  8213. TempTracking: TAllUsedRegs;
  8214. function TryMovArith2Lea(InputInstr: tai): Boolean;
  8215. var
  8216. NextInstr: tai;
  8217. begin
  8218. Result := False;
  8219. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  8220. if not GetNextInstruction(InputInstr, NextInstr) or
  8221. (
  8222. { The FLAGS register isn't always tracked properly, so do not
  8223. perform this optimisation if a conditional statement follows }
  8224. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  8225. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  8226. ) then
  8227. begin
  8228. reference_reset(NewRef, 1, []);
  8229. NewRef.base := taicpu(p).oper[0]^.reg;
  8230. NewRef.scalefactor := 1;
  8231. if taicpu(InputInstr).opcode = A_ADD then
  8232. begin
  8233. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  8234. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  8235. end
  8236. else
  8237. begin
  8238. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  8239. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  8240. end;
  8241. taicpu(p).opcode := A_LEA;
  8242. taicpu(p).loadref(0, NewRef);
  8243. RemoveInstruction(InputInstr);
  8244. Result := True;
  8245. end;
  8246. end;
  8247. begin
  8248. Result:=false;
  8249. { This optimisation adds an instruction, so only do it for speed }
  8250. if not (cs_opt_size in current_settings.optimizerswitches) and
  8251. MatchOpType(taicpu(p), top_const, top_reg) and
  8252. (taicpu(p).oper[0]^.val = 0) then
  8253. begin
  8254. { To avoid compiler warning }
  8255. DestLabel := nil;
  8256. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  8257. InternalError(2021040750);
  8258. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  8259. Exit;
  8260. case hp1.typ of
  8261. ait_align,
  8262. ait_label:
  8263. begin
  8264. { Change:
  8265. mov $0,%reg mov $0,%reg
  8266. @Lbl1: @Lbl1:
  8267. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  8268. je @Lbl2 jne @Lbl2
  8269. To: To:
  8270. mov $0,%reg mov $0,%reg
  8271. jmp @Lbl2 jmp @Lbl3
  8272. (align) (align)
  8273. @Lbl1: @Lbl1:
  8274. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  8275. je @Lbl2 je @Lbl2
  8276. @Lbl3: <-- Only if label exists
  8277. (Not if it's optimised for size)
  8278. }
  8279. if not SkipAligns(hp1, hp1) or not GetNextInstruction(hp1, hp2) then
  8280. Exit;
  8281. if (hp2.typ = ait_instruction) and
  8282. (
  8283. { Register sizes must exactly match }
  8284. (
  8285. (taicpu(hp2).opcode = A_CMP) and
  8286. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  8287. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8288. ) or (
  8289. (taicpu(hp2).opcode = A_TEST) and
  8290. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8291. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  8292. )
  8293. ) and GetNextInstruction(hp2, hp3) and
  8294. (hp3.typ = ait_instruction) and
  8295. (taicpu(hp3).opcode = A_JCC) and
  8296. (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
  8297. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  8298. begin
  8299. { Check condition of jump }
  8300. { Always true? }
  8301. if condition_in(C_E, taicpu(hp3).condition) then
  8302. begin
  8303. { Copy label symbol and obtain matching label entry for the
  8304. conditional jump, as this will be our destination}
  8305. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  8306. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  8307. Result := True;
  8308. end
  8309. { Always false? }
  8310. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  8311. begin
  8312. { This is only worth it if there's a jump to take }
  8313. case hp2.typ of
  8314. ait_instruction:
  8315. begin
  8316. if taicpu(hp2).opcode = A_JMP then
  8317. begin
  8318. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8319. { An unconditional jump follows the conditional jump which will always be false,
  8320. so use this jump's destination for the new jump }
  8321. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  8322. Result := True;
  8323. end
  8324. else if taicpu(hp2).opcode = A_JCC then
  8325. begin
  8326. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  8327. if condition_in(C_E, taicpu(hp2).condition) then
  8328. begin
  8329. { A second conditional jump follows the conditional jump which will always be false,
  8330. while the second jump is always True, so use this jump's destination for the new jump }
  8331. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  8332. Result := True;
  8333. end;
  8334. { Don't risk it if the jump isn't always true (Result remains False) }
  8335. end;
  8336. end;
  8337. else
  8338. { If anything else don't optimise };
  8339. end;
  8340. end;
  8341. if Result then
  8342. begin
  8343. { Just so we have something to insert as a paremeter}
  8344. reference_reset(NewRef, 1, []);
  8345. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  8346. { Now actually load the correct parameter (this also
  8347. increases the reference count) }
  8348. NewInstr.loadsymbol(0, DestLabel, 0);
  8349. if (cs_opt_level3 in current_settings.optimizerswitches) then
  8350. begin
  8351. { Get instruction before original label (may not be p under -O3) }
  8352. if not GetLastInstruction(hp1, hp2) then
  8353. { Shouldn't fail here }
  8354. InternalError(2021040701);
  8355. { Before the aligns too }
  8356. while (hp2.typ = ait_align) do
  8357. if not GetLastInstruction(hp2, hp2) then
  8358. { Shouldn't fail here }
  8359. InternalError(2021040702);
  8360. end
  8361. else
  8362. hp2 := p;
  8363. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  8364. AsmL.InsertAfter(NewInstr, hp2);
  8365. { Add new alignment field }
  8366. (* AsmL.InsertAfter(
  8367. cai_align.create_max(
  8368. current_settings.alignment.jumpalign,
  8369. current_settings.alignment.jumpalignskipmax
  8370. ),
  8371. NewInstr
  8372. ); *)
  8373. end;
  8374. Exit;
  8375. end;
  8376. end;
  8377. else
  8378. ;
  8379. end;
  8380. end;
  8381. if not GetNextInstruction(p, hp1) then
  8382. Exit;
  8383. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8384. and DoMovCmpMemOpt(p, hp1, True) then
  8385. begin
  8386. Result := True;
  8387. Exit;
  8388. end
  8389. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8390. begin
  8391. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8392. further, but we can't just put this jump optimisation in pass 1
  8393. because it tends to perform worse when conditional jumps are
  8394. nearby (e.g. when converting CMOV instructions). [Kit] }
  8395. CopyUsedRegs(TempTracking);
  8396. UpdateUsedRegs(tai(p.Next));
  8397. if OptPass2JMP(hp1) then
  8398. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8399. Result := OptPass1MOV(p);
  8400. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8401. returned True and the instruction is still a MOV, thus checking
  8402. the optimisations below }
  8403. { If OptPass2JMP returned False, no optimisations were done to
  8404. the jump and there are no further optimisations that can be done
  8405. to the MOV instruction on this pass }
  8406. { Restore register state }
  8407. RestoreUsedRegs(TempTracking);
  8408. ReleaseUsedRegs(TempTracking);
  8409. end
  8410. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8411. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8412. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8413. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8414. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8415. begin
  8416. { Change:
  8417. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8418. addl/q $x,%reg2 subl/q $x,%reg2
  8419. To:
  8420. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8421. }
  8422. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8423. { be lazy, checking separately for sub would be slightly better }
  8424. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8425. begin
  8426. TransferUsedRegs(TmpUsedRegs);
  8427. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8428. if TryMovArith2Lea(hp1) then
  8429. begin
  8430. Result := True;
  8431. Exit;
  8432. end
  8433. end
  8434. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8435. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8436. { Same as above, but also adds or subtracts to %reg2 in between.
  8437. It's still valid as long as the flags aren't in use }
  8438. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8439. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8440. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8441. { be lazy, checking separately for sub would be slightly better }
  8442. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8443. begin
  8444. TransferUsedRegs(TmpUsedRegs);
  8445. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8446. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8447. if TryMovArith2Lea(hp2) then
  8448. begin
  8449. Result := True;
  8450. Exit;
  8451. end;
  8452. end;
  8453. end
  8454. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8455. {$ifdef x86_64}
  8456. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8457. {$else x86_64}
  8458. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8459. {$endif x86_64}
  8460. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8461. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8462. { mov reg1, reg2 mov reg1, reg2
  8463. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8464. begin
  8465. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8466. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8467. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8468. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8469. TransferUsedRegs(TmpUsedRegs);
  8470. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8471. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8472. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8473. then
  8474. begin
  8475. RemoveCurrentP(p, hp1);
  8476. Result:=true;
  8477. end;
  8478. exit;
  8479. end
  8480. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8481. IsXCHGAcceptable and
  8482. { XCHG doesn't support 8-byte registers }
  8483. (taicpu(p).opsize <> S_B) and
  8484. MatchInstruction(hp1, A_MOV, []) and
  8485. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8486. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8487. GetNextInstruction(hp1, hp2) and
  8488. MatchInstruction(hp2, A_MOV, []) and
  8489. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8490. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8491. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8492. begin
  8493. { mov %reg1,%reg2
  8494. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8495. mov %reg2,%reg3
  8496. (%reg2 not used afterwards)
  8497. Note that xchg takes 3 cycles to execute, and generally mov's take
  8498. only one cycle apiece, but the first two mov's can be executed in
  8499. parallel, only taking 2 cycles overall. Older processors should
  8500. therefore only optimise for size. [Kit]
  8501. }
  8502. TransferUsedRegs(TmpUsedRegs);
  8503. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8504. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8505. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8506. begin
  8507. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8508. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8509. taicpu(hp1).opcode := A_XCHG;
  8510. RemoveCurrentP(p, hp1);
  8511. RemoveInstruction(hp2);
  8512. Result := True;
  8513. Exit;
  8514. end;
  8515. end
  8516. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8517. MatchInstruction(hp1, A_SAR, []) then
  8518. begin
  8519. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8520. begin
  8521. { the use of %edx also covers the opsize being S_L }
  8522. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8523. begin
  8524. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8525. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8526. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8527. begin
  8528. { Change:
  8529. movl %eax,%edx
  8530. sarl $31,%edx
  8531. To:
  8532. cltd
  8533. }
  8534. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8535. RemoveInstruction(hp1);
  8536. taicpu(p).opcode := A_CDQ;
  8537. taicpu(p).opsize := S_NO;
  8538. taicpu(p).clearop(1);
  8539. taicpu(p).clearop(0);
  8540. taicpu(p).ops:=0;
  8541. Result := True;
  8542. end
  8543. else if (cs_opt_size in current_settings.optimizerswitches) and
  8544. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8545. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8546. begin
  8547. { Change:
  8548. movl %edx,%eax
  8549. sarl $31,%edx
  8550. To:
  8551. movl %edx,%eax
  8552. cltd
  8553. Note that this creates a dependency between the two instructions,
  8554. so only perform if optimising for size.
  8555. }
  8556. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8557. taicpu(hp1).opcode := A_CDQ;
  8558. taicpu(hp1).opsize := S_NO;
  8559. taicpu(hp1).clearop(1);
  8560. taicpu(hp1).clearop(0);
  8561. taicpu(hp1).ops:=0;
  8562. end;
  8563. {$ifndef x86_64}
  8564. end
  8565. { Don't bother if CMOV is supported, because a more optimal
  8566. sequence would have been generated for the Abs() intrinsic }
  8567. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8568. { the use of %eax also covers the opsize being S_L }
  8569. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8570. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8571. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8572. GetNextInstruction(hp1, hp2) and
  8573. MatchInstruction(hp2, A_XOR, [S_L]) and
  8574. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8575. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8576. GetNextInstruction(hp2, hp3) and
  8577. MatchInstruction(hp3, A_SUB, [S_L]) and
  8578. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8579. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8580. begin
  8581. { Change:
  8582. movl %eax,%edx
  8583. sarl $31,%eax
  8584. xorl %eax,%edx
  8585. subl %eax,%edx
  8586. (Instruction that uses %edx)
  8587. (%eax deallocated)
  8588. (%edx deallocated)
  8589. To:
  8590. cltd
  8591. xorl %edx,%eax <-- Note the registers have swapped
  8592. subl %edx,%eax
  8593. (Instruction that uses %eax) <-- %eax rather than %edx
  8594. }
  8595. TransferUsedRegs(TmpUsedRegs);
  8596. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8597. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8598. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8599. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8600. begin
  8601. if GetNextInstruction(hp3, hp4) and
  8602. not RegModifiedByInstruction(NR_EDX, hp4) and
  8603. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8604. begin
  8605. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8606. taicpu(p).opcode := A_CDQ;
  8607. taicpu(p).clearop(1);
  8608. taicpu(p).clearop(0);
  8609. taicpu(p).ops:=0;
  8610. RemoveInstruction(hp1);
  8611. taicpu(hp2).loadreg(0, NR_EDX);
  8612. taicpu(hp2).loadreg(1, NR_EAX);
  8613. taicpu(hp3).loadreg(0, NR_EDX);
  8614. taicpu(hp3).loadreg(1, NR_EAX);
  8615. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8616. { Convert references in the following instruction (hp4) from %edx to %eax }
  8617. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8618. with taicpu(hp4).oper[OperIdx]^ do
  8619. case typ of
  8620. top_reg:
  8621. if getsupreg(reg) = RS_EDX then
  8622. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8623. top_ref:
  8624. begin
  8625. if getsupreg(reg) = RS_EDX then
  8626. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8627. if getsupreg(reg) = RS_EDX then
  8628. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8629. end;
  8630. else
  8631. ;
  8632. end;
  8633. end;
  8634. end;
  8635. {$else x86_64}
  8636. end;
  8637. end
  8638. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8639. { the use of %rdx also covers the opsize being S_Q }
  8640. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8641. begin
  8642. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8643. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8644. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8645. begin
  8646. { Change:
  8647. movq %rax,%rdx
  8648. sarq $63,%rdx
  8649. To:
  8650. cqto
  8651. }
  8652. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8653. RemoveInstruction(hp1);
  8654. taicpu(p).opcode := A_CQO;
  8655. taicpu(p).opsize := S_NO;
  8656. taicpu(p).clearop(1);
  8657. taicpu(p).clearop(0);
  8658. taicpu(p).ops:=0;
  8659. Result := True;
  8660. end
  8661. else if (cs_opt_size in current_settings.optimizerswitches) and
  8662. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8663. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8664. begin
  8665. { Change:
  8666. movq %rdx,%rax
  8667. sarq $63,%rdx
  8668. To:
  8669. movq %rdx,%rax
  8670. cqto
  8671. Note that this creates a dependency between the two instructions,
  8672. so only perform if optimising for size.
  8673. }
  8674. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8675. taicpu(hp1).opcode := A_CQO;
  8676. taicpu(hp1).opsize := S_NO;
  8677. taicpu(hp1).clearop(1);
  8678. taicpu(hp1).clearop(0);
  8679. taicpu(hp1).ops:=0;
  8680. {$endif x86_64}
  8681. end;
  8682. end;
  8683. end
  8684. else if MatchInstruction(hp1, A_MOV, []) and
  8685. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8686. { Though "GetNextInstruction" could be factored out, along with
  8687. the instructions that depend on hp2, it is an expensive call that
  8688. should be delayed for as long as possible, hence we do cheaper
  8689. checks first that are likely to be False. [Kit] }
  8690. begin
  8691. if (
  8692. (
  8693. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8694. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8695. (
  8696. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8697. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8698. )
  8699. ) or
  8700. (
  8701. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8702. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8703. (
  8704. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8705. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8706. )
  8707. )
  8708. ) and
  8709. GetNextInstruction(hp1, hp2) and
  8710. MatchInstruction(hp2, A_SAR, []) and
  8711. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8712. begin
  8713. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8714. begin
  8715. { Change:
  8716. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8717. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8718. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8719. To:
  8720. movl r/m,%eax <- Note the change in register
  8721. cltd
  8722. }
  8723. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8724. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8725. taicpu(p).loadreg(1, NR_EAX);
  8726. taicpu(hp1).opcode := A_CDQ;
  8727. taicpu(hp1).clearop(1);
  8728. taicpu(hp1).clearop(0);
  8729. taicpu(hp1).ops:=0;
  8730. RemoveInstruction(hp2);
  8731. (*
  8732. {$ifdef x86_64}
  8733. end
  8734. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8735. { This code sequence does not get generated - however it might become useful
  8736. if and when 128-bit signed integer types make an appearance, so the code
  8737. is kept here for when it is eventually needed. [Kit] }
  8738. (
  8739. (
  8740. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8741. (
  8742. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8743. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8744. )
  8745. ) or
  8746. (
  8747. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8748. (
  8749. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8750. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8751. )
  8752. )
  8753. ) and
  8754. GetNextInstruction(hp1, hp2) and
  8755. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8756. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8757. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8758. begin
  8759. { Change:
  8760. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8761. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8762. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8763. To:
  8764. movq r/m,%rax <- Note the change in register
  8765. cqto
  8766. }
  8767. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8768. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8769. taicpu(p).loadreg(1, NR_RAX);
  8770. taicpu(hp1).opcode := A_CQO;
  8771. taicpu(hp1).clearop(1);
  8772. taicpu(hp1).clearop(0);
  8773. taicpu(hp1).ops:=0;
  8774. RemoveInstruction(hp2);
  8775. {$endif x86_64}
  8776. *)
  8777. end;
  8778. end;
  8779. {$ifdef x86_64}
  8780. end
  8781. else if (taicpu(p).opsize = S_L) and
  8782. (taicpu(p).oper[1]^.typ = top_reg) and
  8783. (
  8784. MatchInstruction(hp1, A_MOV,[]) and
  8785. (taicpu(hp1).opsize = S_L) and
  8786. (taicpu(hp1).oper[1]^.typ = top_reg)
  8787. ) and (
  8788. GetNextInstruction(hp1, hp2) and
  8789. (tai(hp2).typ=ait_instruction) and
  8790. (taicpu(hp2).opsize = S_Q) and
  8791. (
  8792. (
  8793. MatchInstruction(hp2, A_ADD,[]) and
  8794. (taicpu(hp2).opsize = S_Q) and
  8795. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8796. (
  8797. (
  8798. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8799. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8800. ) or (
  8801. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8802. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8803. )
  8804. )
  8805. ) or (
  8806. MatchInstruction(hp2, A_LEA,[]) and
  8807. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8808. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8809. (
  8810. (
  8811. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8812. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8813. ) or (
  8814. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8815. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  8816. )
  8817. ) and (
  8818. (
  8819. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8820. ) or (
  8821. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8822. )
  8823. )
  8824. )
  8825. )
  8826. ) and (
  8827. GetNextInstruction(hp2, hp3) and
  8828. MatchInstruction(hp3, A_SHR,[]) and
  8829. (taicpu(hp3).opsize = S_Q) and
  8830. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8831. (taicpu(hp3).oper[0]^.val = 1) and
  8832. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  8833. ) then
  8834. begin
  8835. { Change movl x, reg1d movl x, reg1d
  8836. movl y, reg2d movl y, reg2d
  8837. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  8838. shrq $1, reg1q shrq $1, reg1q
  8839. ( reg1d and reg2d can be switched around in the first two instructions )
  8840. To movl x, reg1d
  8841. addl y, reg1d
  8842. rcrl $1, reg1d
  8843. This corresponds to the common expression (x + y) shr 1, where
  8844. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  8845. smaller code, but won't account for x + y causing an overflow). [Kit]
  8846. }
  8847. DebugMsg(SPeepholeOptimization + 'MovMov*Shr2MovMov*Rcr', p);
  8848. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8849. { Change first MOV command to have the same register as the final output }
  8850. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  8851. else
  8852. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  8853. { Change second MOV command to an ADD command. This is easier than
  8854. converting the existing command because it means we don't have to
  8855. touch 'y', which might be a complicated reference, and also the
  8856. fact that the third command might either be ADD or LEA. [Kit] }
  8857. taicpu(hp1).opcode := A_ADD;
  8858. { Delete old ADD/LEA instruction }
  8859. RemoveInstruction(hp2);
  8860. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  8861. taicpu(hp3).opcode := A_RCR;
  8862. taicpu(hp3).changeopsize(S_L);
  8863. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  8864. {$endif x86_64}
  8865. end;
  8866. if FuncMov2Func(p, hp1) then
  8867. begin
  8868. Result := True;
  8869. Exit;
  8870. end;
  8871. end;
  8872. {$push}
  8873. {$q-}{$r-}
  8874. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  8875. var
  8876. ThisReg: TRegister;
  8877. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  8878. TargetSubReg: TSubRegister;
  8879. hp1, hp2: tai;
  8880. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  8881. { Store list of found instructions so we don't have to call
  8882. GetNextInstructionUsingReg multiple times }
  8883. InstrList: array of taicpu;
  8884. InstrMax, Index: Integer;
  8885. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  8886. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  8887. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  8888. WorkingValue: TCgInt;
  8889. PreMessage: string;
  8890. { Data flow analysis }
  8891. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  8892. BitwiseOnly, OrXorUsed,
  8893. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  8894. function CheckOverflowConditions: Boolean;
  8895. begin
  8896. Result := True;
  8897. if (TestValSignedMax > SignedUpperLimit) then
  8898. UpperSignedOverflow := True;
  8899. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  8900. LowerSignedOverflow := True;
  8901. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  8902. LowerUnsignedOverflow := True;
  8903. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  8904. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  8905. begin
  8906. { Absolute overflow }
  8907. Result := False;
  8908. Exit;
  8909. end;
  8910. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  8911. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  8912. ShiftDownOverflow := True;
  8913. if (TestValMin < 0) or (TestValMax < 0) then
  8914. begin
  8915. LowerUnsignedOverflow := True;
  8916. UpperUnsignedOverflow := True;
  8917. end;
  8918. end;
  8919. function AdjustInitialLoadAndSize: Boolean;
  8920. begin
  8921. Result := False;
  8922. if not p_removed then
  8923. begin
  8924. if TargetSize = MinSize then
  8925. begin
  8926. { Convert the input MOVZX to a MOV }
  8927. if (taicpu(p).oper[0]^.typ = top_reg) and
  8928. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8929. begin
  8930. { Or remove it completely! }
  8931. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  8932. RemoveCurrentP(p);
  8933. p_removed := True;
  8934. end
  8935. else
  8936. begin
  8937. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  8938. taicpu(p).opcode := A_MOV;
  8939. taicpu(p).oper[1]^.reg := ThisReg;
  8940. taicpu(p).opsize := TargetSize;
  8941. end;
  8942. Result := True;
  8943. end
  8944. else if TargetSize <> MaxSize then
  8945. begin
  8946. case MaxSize of
  8947. S_L:
  8948. if TargetSize = S_W then
  8949. begin
  8950. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  8951. taicpu(p).opsize := S_BW;
  8952. taicpu(p).oper[1]^.reg := ThisReg;
  8953. Result := True;
  8954. end
  8955. else
  8956. InternalError(2020112341);
  8957. S_W:
  8958. if TargetSize = S_L then
  8959. begin
  8960. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  8961. taicpu(p).opsize := S_BL;
  8962. taicpu(p).oper[1]^.reg := ThisReg;
  8963. Result := True;
  8964. end
  8965. else
  8966. InternalError(2020112342);
  8967. else
  8968. ;
  8969. end;
  8970. end
  8971. else if not hp1_removed and not RegInUse then
  8972. begin
  8973. { If we have something like:
  8974. movzbl (oper),%regd
  8975. add x, %regd
  8976. movzbl %regb, %regd
  8977. We can reduce the register size to the input of the final
  8978. movzbl instruction. Overflows won't have any effect.
  8979. }
  8980. if (taicpu(p).opsize in [S_BW, S_BL]) and
  8981. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8982. begin
  8983. TargetSize := S_B;
  8984. setsubreg(ThisReg, R_SUBL);
  8985. Result := True;
  8986. end
  8987. else if (taicpu(p).opsize = S_WL) and
  8988. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8989. begin
  8990. TargetSize := S_W;
  8991. setsubreg(ThisReg, R_SUBW);
  8992. Result := True;
  8993. end;
  8994. if Result then
  8995. begin
  8996. { Convert the input MOVZX to a MOV }
  8997. if (taicpu(p).oper[0]^.typ = top_reg) and
  8998. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8999. begin
  9000. { Or remove it completely! }
  9001. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  9002. RemoveCurrentP(p);
  9003. p_removed := True;
  9004. end
  9005. else
  9006. begin
  9007. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  9008. taicpu(p).opcode := A_MOV;
  9009. taicpu(p).oper[1]^.reg := ThisReg;
  9010. taicpu(p).opsize := TargetSize;
  9011. end;
  9012. end;
  9013. end;
  9014. end;
  9015. end;
  9016. procedure AdjustFinalLoad;
  9017. begin
  9018. if not LowerUnsignedOverflow then
  9019. begin
  9020. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  9021. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  9022. begin
  9023. { Convert the output MOVZX to a MOV }
  9024. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9025. begin
  9026. { Make sure the zero-expansion covers at least the minimum size (fixes i40003) }
  9027. if (MinSize = S_B) or
  9028. (not ShiftDownOverflow and (TryShiftDown = S_B)) or
  9029. ((MinSize = S_W) and (taicpu(hp1).opsize = S_WL)) then
  9030. begin
  9031. { Remove it completely! }
  9032. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  9033. { Be careful; if p = hp1 and p was also removed, p
  9034. will become a dangling pointer }
  9035. if p = hp1 then
  9036. begin
  9037. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9038. p_removed := True;
  9039. end
  9040. else
  9041. RemoveInstruction(hp1);
  9042. hp1_removed := True;
  9043. end;
  9044. end
  9045. else
  9046. begin
  9047. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  9048. taicpu(hp1).opcode := A_MOV;
  9049. taicpu(hp1).oper[0]^.reg := ThisReg;
  9050. taicpu(hp1).opsize := TargetSize;
  9051. end;
  9052. end
  9053. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  9054. begin
  9055. { Need to change the size of the output }
  9056. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  9057. taicpu(hp1).oper[0]^.reg := ThisReg;
  9058. taicpu(hp1).opsize := S_BL;
  9059. end;
  9060. end;
  9061. end;
  9062. function CompressInstructions: Boolean;
  9063. var
  9064. LocalIndex: Integer;
  9065. begin
  9066. Result := False;
  9067. { The objective here is to try to find a combination that
  9068. removes one of the MOV/Z instructions. }
  9069. if (
  9070. (taicpu(p).oper[0]^.typ <> top_reg) or
  9071. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  9072. ) and
  9073. (taicpu(hp1).oper[1]^.typ = top_reg) and
  9074. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9075. begin
  9076. { Make a preference to remove the second MOVZX instruction }
  9077. case taicpu(hp1).opsize of
  9078. S_BL, S_WL:
  9079. begin
  9080. TargetSize := S_L;
  9081. TargetSubReg := R_SUBD;
  9082. end;
  9083. S_BW:
  9084. begin
  9085. TargetSize := S_W;
  9086. TargetSubReg := R_SUBW;
  9087. end;
  9088. else
  9089. InternalError(2020112302);
  9090. end;
  9091. end
  9092. else
  9093. begin
  9094. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9095. begin
  9096. { Exceeded lower bound but not upper bound }
  9097. TargetSize := MaxSize;
  9098. end
  9099. else if not LowerUnsignedOverflow then
  9100. begin
  9101. { Size didn't exceed lower bound }
  9102. TargetSize := MinSize;
  9103. end
  9104. else
  9105. Exit;
  9106. end;
  9107. case TargetSize of
  9108. S_B:
  9109. TargetSubReg := R_SUBL;
  9110. S_W:
  9111. TargetSubReg := R_SUBW;
  9112. S_L:
  9113. TargetSubReg := R_SUBD;
  9114. else
  9115. InternalError(2020112350);
  9116. end;
  9117. { Update the register to its new size }
  9118. setsubreg(ThisReg, TargetSubReg);
  9119. RegInUse := False;
  9120. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9121. begin
  9122. { Check to see if the active register is used afterwards;
  9123. if not, we can change it and make a saving. }
  9124. TransferUsedRegs(TmpUsedRegs);
  9125. { The target register may be marked as in use to cross
  9126. a jump to a distant label, so exclude it }
  9127. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  9128. hp2 := p;
  9129. repeat
  9130. { Explicitly check for the excluded register (don't include the first
  9131. instruction as it may be reading from here }
  9132. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  9133. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  9134. begin
  9135. RegInUse := True;
  9136. Break;
  9137. end;
  9138. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  9139. if not GetNextInstruction(hp2, hp2) then
  9140. InternalError(2020112340);
  9141. until (hp2 = hp1);
  9142. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9143. { We might still be able to get away with this }
  9144. RegInUse := not
  9145. (
  9146. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  9147. (hp2.typ = ait_instruction) and
  9148. (
  9149. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9150. instruction that doesn't actually contain ThisReg }
  9151. (cs_opt_level3 in current_settings.optimizerswitches) or
  9152. RegInInstruction(ThisReg, hp2)
  9153. ) and
  9154. RegLoadedWithNewValue(ThisReg, hp2)
  9155. );
  9156. if not RegInUse then
  9157. begin
  9158. { Force the register size to the same as this instruction so it can be removed}
  9159. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  9160. begin
  9161. TargetSize := S_L;
  9162. TargetSubReg := R_SUBD;
  9163. end
  9164. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  9165. begin
  9166. TargetSize := S_W;
  9167. TargetSubReg := R_SUBW;
  9168. end;
  9169. ThisReg := taicpu(hp1).oper[1]^.reg;
  9170. setsubreg(ThisReg, TargetSubReg);
  9171. RegChanged := True;
  9172. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  9173. TransferUsedRegs(TmpUsedRegs);
  9174. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  9175. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  9176. if p = hp1 then
  9177. begin
  9178. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  9179. p_removed := True;
  9180. end
  9181. else
  9182. RemoveInstruction(hp1);
  9183. hp1_removed := True;
  9184. { Instruction will become "mov %reg,%reg" }
  9185. if not p_removed and (taicpu(p).opcode = A_MOV) and
  9186. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  9187. begin
  9188. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  9189. RemoveCurrentP(p);
  9190. p_removed := True;
  9191. end
  9192. else
  9193. taicpu(p).oper[1]^.reg := ThisReg;
  9194. Result := True;
  9195. end
  9196. else
  9197. begin
  9198. if TargetSize <> MaxSize then
  9199. begin
  9200. { Since the register is in use, we have to force it to
  9201. MaxSize otherwise part of it may become undefined later on }
  9202. TargetSize := MaxSize;
  9203. case TargetSize of
  9204. S_B:
  9205. TargetSubReg := R_SUBL;
  9206. S_W:
  9207. TargetSubReg := R_SUBW;
  9208. S_L:
  9209. TargetSubReg := R_SUBD;
  9210. else
  9211. InternalError(2020112351);
  9212. end;
  9213. setsubreg(ThisReg, TargetSubReg);
  9214. end;
  9215. AdjustFinalLoad;
  9216. end;
  9217. end
  9218. else
  9219. AdjustFinalLoad;
  9220. Result := AdjustInitialLoadAndSize or Result;
  9221. { Now go through every instruction we found and change the
  9222. size. If TargetSize = MaxSize, then almost no changes are
  9223. needed and Result can remain False if it hasn't been set
  9224. yet.
  9225. If RegChanged is True, then the register requires changing
  9226. and so the point about TargetSize = MaxSize doesn't apply. }
  9227. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  9228. begin
  9229. for LocalIndex := 0 to InstrMax do
  9230. begin
  9231. { If p_removed is true, then the original MOV/Z was removed
  9232. and removing the AND instruction may not be safe if it
  9233. appears first }
  9234. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  9235. InternalError(2020112310);
  9236. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  9237. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  9238. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  9239. InstrList[LocalIndex].opsize := TargetSize;
  9240. end;
  9241. Result := True;
  9242. end;
  9243. end;
  9244. begin
  9245. Result := False;
  9246. p_removed := False;
  9247. hp1_removed := False;
  9248. ThisReg := taicpu(p).oper[1]^.reg;
  9249. { Check for:
  9250. movs/z ###,%ecx (or %cx or %rcx)
  9251. ...
  9252. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9253. (dealloc %ecx)
  9254. Change to:
  9255. mov ###,%cl (if ### = %cl, then remove completely)
  9256. ...
  9257. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  9258. }
  9259. if (getsupreg(ThisReg) = RS_ECX) and
  9260. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  9261. (hp1.typ = ait_instruction) and
  9262. (
  9263. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9264. instruction that doesn't actually contain ECX }
  9265. (cs_opt_level3 in current_settings.optimizerswitches) or
  9266. RegInInstruction(NR_ECX, hp1) or
  9267. (
  9268. { It's common for the shift/rotate's read/write register to be
  9269. initialised in between, so under -O2 and under, search ahead
  9270. one more instruction
  9271. }
  9272. GetNextInstruction(hp1, hp1) and
  9273. (hp1.typ = ait_instruction) and
  9274. RegInInstruction(NR_ECX, hp1)
  9275. )
  9276. ) and
  9277. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  9278. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  9279. begin
  9280. TransferUsedRegs(TmpUsedRegs);
  9281. hp2 := p;
  9282. repeat
  9283. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  9284. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  9285. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  9286. begin
  9287. case taicpu(p).opsize of
  9288. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9289. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  9290. begin
  9291. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  9292. RemoveCurrentP(p);
  9293. end
  9294. else
  9295. begin
  9296. taicpu(p).opcode := A_MOV;
  9297. taicpu(p).opsize := S_B;
  9298. taicpu(p).oper[1]^.reg := NR_CL;
  9299. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  9300. end;
  9301. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9302. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  9303. begin
  9304. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  9305. RemoveCurrentP(p);
  9306. end
  9307. else
  9308. begin
  9309. taicpu(p).opcode := A_MOV;
  9310. taicpu(p).opsize := S_W;
  9311. taicpu(p).oper[1]^.reg := NR_CX;
  9312. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  9313. end;
  9314. {$ifdef x86_64}
  9315. S_LQ:
  9316. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  9317. begin
  9318. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  9319. RemoveCurrentP(p);
  9320. end
  9321. else
  9322. begin
  9323. taicpu(p).opcode := A_MOV;
  9324. taicpu(p).opsize := S_L;
  9325. taicpu(p).oper[1]^.reg := NR_ECX;
  9326. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  9327. end;
  9328. {$endif x86_64}
  9329. else
  9330. InternalError(2021120401);
  9331. end;
  9332. Result := True;
  9333. Exit;
  9334. end;
  9335. end;
  9336. { This is anything but quick! }
  9337. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  9338. Exit;
  9339. SetLength(InstrList, 0);
  9340. InstrMax := -1;
  9341. case taicpu(p).opsize of
  9342. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  9343. begin
  9344. {$if defined(i386) or defined(i8086)}
  9345. { If the target size is 8-bit, make sure we can actually encode it }
  9346. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  9347. Exit;
  9348. {$endif i386 or i8086}
  9349. LowerLimit := $FF;
  9350. SignedLowerLimit := $7F;
  9351. SignedLowerLimitBottom := -128;
  9352. MinSize := S_B;
  9353. if taicpu(p).opsize = S_BW then
  9354. begin
  9355. MaxSize := S_W;
  9356. UpperLimit := $FFFF;
  9357. SignedUpperLimit := $7FFF;
  9358. SignedUpperLimitBottom := -32768;
  9359. end
  9360. else
  9361. begin
  9362. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  9363. MaxSize := S_L;
  9364. UpperLimit := $FFFFFFFF;
  9365. SignedUpperLimit := $7FFFFFFF;
  9366. SignedUpperLimitBottom := -2147483648;
  9367. end;
  9368. end;
  9369. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  9370. begin
  9371. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  9372. LowerLimit := $FFFF;
  9373. SignedLowerLimit := $7FFF;
  9374. SignedLowerLimitBottom := -32768;
  9375. UpperLimit := $FFFFFFFF;
  9376. SignedUpperLimit := $7FFFFFFF;
  9377. SignedUpperLimitBottom := -2147483648;
  9378. MinSize := S_W;
  9379. MaxSize := S_L;
  9380. end;
  9381. {$ifdef x86_64}
  9382. S_LQ:
  9383. begin
  9384. { Both the lower and upper limits are set to 32-bit. If a limit
  9385. is breached, then optimisation is impossible }
  9386. LowerLimit := $FFFFFFFF;
  9387. SignedLowerLimit := $7FFFFFFF;
  9388. SignedLowerLimitBottom := -2147483648;
  9389. UpperLimit := $FFFFFFFF;
  9390. SignedUpperLimit := $7FFFFFFF;
  9391. SignedUpperLimitBottom := -2147483648;
  9392. MinSize := S_L;
  9393. MaxSize := S_L;
  9394. end;
  9395. {$endif x86_64}
  9396. else
  9397. InternalError(2020112301);
  9398. end;
  9399. TestValMin := 0;
  9400. TestValMax := LowerLimit;
  9401. TestValSignedMax := SignedLowerLimit;
  9402. TryShiftDownLimit := LowerLimit;
  9403. TryShiftDown := S_NO;
  9404. ShiftDownOverflow := False;
  9405. RegChanged := False;
  9406. BitwiseOnly := True;
  9407. OrXorUsed := False;
  9408. UpperSignedOverflow := False;
  9409. LowerSignedOverflow := False;
  9410. UpperUnsignedOverflow := False;
  9411. LowerUnsignedOverflow := False;
  9412. hp1 := p;
  9413. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9414. (hp1.typ = ait_instruction) and
  9415. (
  9416. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9417. instruction that doesn't actually contain ThisReg }
  9418. (cs_opt_level3 in current_settings.optimizerswitches) or
  9419. { This allows this Movx optimisation to work through the SETcc instructions
  9420. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9421. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9422. skip over these SETcc instructions). }
  9423. (taicpu(hp1).opcode = A_SETcc) or
  9424. RegInInstruction(ThisReg, hp1)
  9425. ) do
  9426. begin
  9427. case taicpu(hp1).opcode of
  9428. A_INC,A_DEC:
  9429. begin
  9430. { Has to be an exact match on the register }
  9431. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9432. Break;
  9433. if taicpu(hp1).opcode = A_INC then
  9434. begin
  9435. Inc(TestValMin);
  9436. Inc(TestValMax);
  9437. Inc(TestValSignedMax);
  9438. end
  9439. else
  9440. begin
  9441. Dec(TestValMin);
  9442. Dec(TestValMax);
  9443. Dec(TestValSignedMax);
  9444. end;
  9445. end;
  9446. A_TEST, A_CMP:
  9447. begin
  9448. if (
  9449. { Too high a risk of non-linear behaviour that breaks DFA
  9450. here, unless it's cmp $0,%reg, which is equivalent to
  9451. test %reg,%reg }
  9452. OrXorUsed and
  9453. (taicpu(hp1).opcode = A_CMP) and
  9454. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9455. ) or
  9456. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9457. { Has to be an exact match on the register }
  9458. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9459. (
  9460. { Permit "test %reg,%reg" }
  9461. (taicpu(hp1).opcode = A_TEST) and
  9462. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9463. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9464. ) or
  9465. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9466. { Make sure the comparison value is not smaller than the
  9467. smallest allowed signed value for the minimum size (e.g.
  9468. -128 for 8-bit) }
  9469. not (
  9470. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9471. { Is it in the negative range? }
  9472. (
  9473. (taicpu(hp1).oper[0]^.val < 0) and
  9474. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9475. )
  9476. ) then
  9477. Break;
  9478. { Check to see if the active register is used afterwards }
  9479. TransferUsedRegs(TmpUsedRegs);
  9480. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9481. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9482. begin
  9483. { Make sure the comparison or any previous instructions
  9484. hasn't pushed the test values outside of the range of
  9485. MinSize }
  9486. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9487. begin
  9488. { Exceeded lower bound but not upper bound }
  9489. Exit;
  9490. end
  9491. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9492. begin
  9493. { Size didn't exceed lower bound }
  9494. TargetSize := MinSize;
  9495. end
  9496. else
  9497. Break;
  9498. case TargetSize of
  9499. S_B:
  9500. TargetSubReg := R_SUBL;
  9501. S_W:
  9502. TargetSubReg := R_SUBW;
  9503. S_L:
  9504. TargetSubReg := R_SUBD;
  9505. else
  9506. InternalError(2021051002);
  9507. end;
  9508. if TargetSize <> MaxSize then
  9509. begin
  9510. { Update the register to its new size }
  9511. setsubreg(ThisReg, TargetSubReg);
  9512. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9513. taicpu(hp1).oper[1]^.reg := ThisReg;
  9514. taicpu(hp1).opsize := TargetSize;
  9515. { Convert the input MOVZX to a MOV if necessary }
  9516. AdjustInitialLoadAndSize;
  9517. if (InstrMax >= 0) then
  9518. begin
  9519. for Index := 0 to InstrMax do
  9520. begin
  9521. { If p_removed is true, then the original MOV/Z was removed
  9522. and removing the AND instruction may not be safe if it
  9523. appears first }
  9524. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9525. InternalError(2020112311);
  9526. if InstrList[Index].oper[0]^.typ = top_reg then
  9527. InstrList[Index].oper[0]^.reg := ThisReg;
  9528. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9529. InstrList[Index].opsize := MinSize;
  9530. end;
  9531. end;
  9532. Result := True;
  9533. end;
  9534. Exit;
  9535. end;
  9536. end;
  9537. A_SETcc:
  9538. begin
  9539. { This allows this Movx optimisation to work through the SETcc instructions
  9540. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9541. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9542. skip over these SETcc instructions). }
  9543. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9544. { Of course, break out if the current register is used }
  9545. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9546. Break
  9547. else
  9548. { We must use Continue so the instruction doesn't get added
  9549. to InstrList }
  9550. Continue;
  9551. end;
  9552. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9553. begin
  9554. if
  9555. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9556. { Has to be an exact match on the register }
  9557. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9558. (
  9559. (
  9560. (taicpu(hp1).oper[0]^.typ = top_const) and
  9561. (
  9562. (
  9563. (taicpu(hp1).opcode = A_SHL) and
  9564. (
  9565. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9566. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9567. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9568. )
  9569. ) or (
  9570. (taicpu(hp1).opcode <> A_SHL) and
  9571. (
  9572. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9573. { Is it in the negative range? }
  9574. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9575. )
  9576. )
  9577. )
  9578. ) or (
  9579. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9580. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9581. )
  9582. ) then
  9583. Break;
  9584. { Only process OR and XOR if there are only bitwise operations,
  9585. since otherwise they can too easily fool the data flow
  9586. analysis (they can cause non-linear behaviour) }
  9587. case taicpu(hp1).opcode of
  9588. A_ADD:
  9589. begin
  9590. if OrXorUsed then
  9591. { Too high a risk of non-linear behaviour that breaks DFA here }
  9592. Break
  9593. else
  9594. BitwiseOnly := False;
  9595. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9596. begin
  9597. TestValMin := TestValMin * 2;
  9598. TestValMax := TestValMax * 2;
  9599. TestValSignedMax := TestValSignedMax * 2;
  9600. end
  9601. else
  9602. begin
  9603. WorkingValue := taicpu(hp1).oper[0]^.val;
  9604. TestValMin := TestValMin + WorkingValue;
  9605. TestValMax := TestValMax + WorkingValue;
  9606. TestValSignedMax := TestValSignedMax + WorkingValue;
  9607. end;
  9608. end;
  9609. A_SUB:
  9610. begin
  9611. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9612. begin
  9613. TestValMin := 0;
  9614. TestValMax := 0;
  9615. TestValSignedMax := 0;
  9616. end
  9617. else
  9618. begin
  9619. if OrXorUsed then
  9620. { Too high a risk of non-linear behaviour that breaks DFA here }
  9621. Break
  9622. else
  9623. BitwiseOnly := False;
  9624. WorkingValue := taicpu(hp1).oper[0]^.val;
  9625. TestValMin := TestValMin - WorkingValue;
  9626. TestValMax := TestValMax - WorkingValue;
  9627. TestValSignedMax := TestValSignedMax - WorkingValue;
  9628. end;
  9629. end;
  9630. A_AND:
  9631. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9632. begin
  9633. { we might be able to go smaller if AND appears first }
  9634. if InstrMax = -1 then
  9635. case MinSize of
  9636. S_B:
  9637. ;
  9638. S_W:
  9639. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9640. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9641. begin
  9642. TryShiftDown := S_B;
  9643. TryShiftDownLimit := $FF;
  9644. end;
  9645. S_L:
  9646. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9647. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9648. begin
  9649. TryShiftDown := S_B;
  9650. TryShiftDownLimit := $FF;
  9651. end
  9652. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9653. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9654. begin
  9655. TryShiftDown := S_W;
  9656. TryShiftDownLimit := $FFFF;
  9657. end;
  9658. else
  9659. InternalError(2020112320);
  9660. end;
  9661. WorkingValue := taicpu(hp1).oper[0]^.val;
  9662. TestValMin := TestValMin and WorkingValue;
  9663. TestValMax := TestValMax and WorkingValue;
  9664. TestValSignedMax := TestValSignedMax and WorkingValue;
  9665. end;
  9666. A_OR:
  9667. begin
  9668. if not BitwiseOnly then
  9669. Break;
  9670. OrXorUsed := True;
  9671. WorkingValue := taicpu(hp1).oper[0]^.val;
  9672. TestValMin := TestValMin or WorkingValue;
  9673. TestValMax := TestValMax or WorkingValue;
  9674. TestValSignedMax := TestValSignedMax or WorkingValue;
  9675. end;
  9676. A_XOR:
  9677. begin
  9678. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9679. begin
  9680. TestValMin := 0;
  9681. TestValMax := 0;
  9682. TestValSignedMax := 0;
  9683. end
  9684. else
  9685. begin
  9686. if not BitwiseOnly then
  9687. Break;
  9688. OrXorUsed := True;
  9689. WorkingValue := taicpu(hp1).oper[0]^.val;
  9690. TestValMin := TestValMin xor WorkingValue;
  9691. TestValMax := TestValMax xor WorkingValue;
  9692. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9693. end;
  9694. end;
  9695. A_SHL:
  9696. begin
  9697. BitwiseOnly := False;
  9698. WorkingValue := taicpu(hp1).oper[0]^.val;
  9699. TestValMin := TestValMin shl WorkingValue;
  9700. TestValMax := TestValMax shl WorkingValue;
  9701. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9702. end;
  9703. A_SHR,
  9704. { The first instruction was MOVZX, so the value won't be negative }
  9705. A_SAR:
  9706. begin
  9707. if InstrMax <> -1 then
  9708. BitwiseOnly := False
  9709. else
  9710. { we might be able to go smaller if SHR appears first }
  9711. case MinSize of
  9712. S_B:
  9713. ;
  9714. S_W:
  9715. if (taicpu(hp1).oper[0]^.val >= 8) then
  9716. begin
  9717. TryShiftDown := S_B;
  9718. TryShiftDownLimit := $FF;
  9719. TryShiftDownSignedLimit := $7F;
  9720. TryShiftDownSignedLimitLower := -128;
  9721. end;
  9722. S_L:
  9723. if (taicpu(hp1).oper[0]^.val >= 24) then
  9724. begin
  9725. TryShiftDown := S_B;
  9726. TryShiftDownLimit := $FF;
  9727. TryShiftDownSignedLimit := $7F;
  9728. TryShiftDownSignedLimitLower := -128;
  9729. end
  9730. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9731. begin
  9732. TryShiftDown := S_W;
  9733. TryShiftDownLimit := $FFFF;
  9734. TryShiftDownSignedLimit := $7FFF;
  9735. TryShiftDownSignedLimitLower := -32768;
  9736. end;
  9737. else
  9738. InternalError(2020112321);
  9739. end;
  9740. WorkingValue := taicpu(hp1).oper[0]^.val;
  9741. if taicpu(hp1).opcode = A_SAR then
  9742. begin
  9743. TestValMin := SarInt64(TestValMin, WorkingValue);
  9744. TestValMax := SarInt64(TestValMax, WorkingValue);
  9745. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9746. end
  9747. else
  9748. begin
  9749. TestValMin := TestValMin shr WorkingValue;
  9750. TestValMax := TestValMax shr WorkingValue;
  9751. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9752. end;
  9753. end;
  9754. else
  9755. InternalError(2020112303);
  9756. end;
  9757. end;
  9758. (*
  9759. A_IMUL:
  9760. case taicpu(hp1).ops of
  9761. 2:
  9762. begin
  9763. if not MatchOpType(hp1, top_reg, top_reg) or
  9764. { Has to be an exact match on the register }
  9765. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9766. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9767. Break;
  9768. TestValMin := TestValMin * TestValMin;
  9769. TestValMax := TestValMax * TestValMax;
  9770. TestValSignedMax := TestValSignedMax * TestValMax;
  9771. end;
  9772. 3:
  9773. begin
  9774. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9775. { Has to be an exact match on the register }
  9776. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9777. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9778. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9779. { Is it in the negative range? }
  9780. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9781. Break;
  9782. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9783. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9784. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9785. end;
  9786. else
  9787. Break;
  9788. end;
  9789. A_IDIV:
  9790. case taicpu(hp1).ops of
  9791. 3:
  9792. begin
  9793. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9794. { Has to be an exact match on the register }
  9795. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9796. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9797. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9798. { Is it in the negative range? }
  9799. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9800. Break;
  9801. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9802. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9803. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9804. end;
  9805. else
  9806. Break;
  9807. end;
  9808. *)
  9809. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9810. begin
  9811. { If there are no instructions in between, then we might be able to make a saving }
  9812. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9813. Break;
  9814. { We have something like:
  9815. movzbw %dl,%dx
  9816. ...
  9817. movswl %dx,%edx
  9818. Change the latter to a zero-extension then enter the
  9819. A_MOVZX case branch.
  9820. }
  9821. {$ifdef x86_64}
  9822. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9823. begin
  9824. { this becomes a zero extension from 32-bit to 64-bit, but
  9825. the upper 32 bits are already zero, so just delete the
  9826. instruction }
  9827. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  9828. RemoveInstruction(hp1);
  9829. Result := True;
  9830. Exit;
  9831. end
  9832. else
  9833. {$endif x86_64}
  9834. begin
  9835. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  9836. taicpu(hp1).opcode := A_MOVZX;
  9837. {$ifdef x86_64}
  9838. case taicpu(hp1).opsize of
  9839. S_BQ:
  9840. begin
  9841. taicpu(hp1).opsize := S_BL;
  9842. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9843. end;
  9844. S_WQ:
  9845. begin
  9846. taicpu(hp1).opsize := S_WL;
  9847. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9848. end;
  9849. S_LQ:
  9850. begin
  9851. taicpu(hp1).opcode := A_MOV;
  9852. taicpu(hp1).opsize := S_L;
  9853. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9854. { In this instance, we need to break out because the
  9855. instruction is no longer MOVZX or MOVSXD }
  9856. Result := True;
  9857. Exit;
  9858. end;
  9859. else
  9860. ;
  9861. end;
  9862. {$endif x86_64}
  9863. Result := CompressInstructions;
  9864. Exit;
  9865. end;
  9866. end;
  9867. A_MOVZX:
  9868. begin
  9869. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  9870. Break;
  9871. if (InstrMax = -1) then
  9872. begin
  9873. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  9874. begin
  9875. { Optimise around i40003 }
  9876. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) and
  9877. (taicpu(p).opsize = S_WL) and (taicpu(hp1).opsize = S_BL)
  9878. {$ifndef x86_64}
  9879. and (
  9880. (taicpu(p).oper[0]^.typ <> top_reg) or
  9881. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  9882. (GetSupReg(taicpu(p).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  9883. )
  9884. {$endif not x86_64}
  9885. then
  9886. begin
  9887. if (taicpu(p).oper[0]^.typ = top_reg) then
  9888. setsubreg(taicpu(p).oper[0]^.reg, R_SUBL);
  9889. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 1', p);
  9890. taicpu(p).opsize := S_BL;
  9891. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2a', hp1);
  9892. RemoveInstruction(hp1);
  9893. Result := True;
  9894. Exit;
  9895. end;
  9896. end
  9897. else
  9898. begin
  9899. { Will return false if the second parameter isn't ThisReg
  9900. (can happen on -O2 and under) }
  9901. if Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9902. begin
  9903. { The two MOVZX instructions are adjacent, so remove the first one }
  9904. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  9905. RemoveCurrentP(p);
  9906. Result := True;
  9907. Exit;
  9908. end;
  9909. Break;
  9910. end;
  9911. end;
  9912. Result := CompressInstructions;
  9913. Exit;
  9914. end;
  9915. else
  9916. { This includes ADC, SBB and IDIV }
  9917. Break;
  9918. end;
  9919. if not CheckOverflowConditions then
  9920. Break;
  9921. { Contains highest index (so instruction count - 1) }
  9922. Inc(InstrMax);
  9923. if InstrMax > High(InstrList) then
  9924. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9925. InstrList[InstrMax] := taicpu(hp1);
  9926. end;
  9927. end;
  9928. {$pop}
  9929. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  9930. var
  9931. hp1 : tai;
  9932. begin
  9933. Result:=false;
  9934. if (taicpu(p).ops >= 2) and
  9935. ((taicpu(p).oper[0]^.typ = top_const) or
  9936. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  9937. (taicpu(p).oper[1]^.typ = top_reg) and
  9938. ((taicpu(p).ops = 2) or
  9939. ((taicpu(p).oper[2]^.typ = top_reg) and
  9940. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  9941. GetLastInstruction(p,hp1) and
  9942. MatchInstruction(hp1,A_MOV,[]) and
  9943. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9944. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9945. begin
  9946. TransferUsedRegs(TmpUsedRegs);
  9947. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  9948. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  9949. { change
  9950. mov reg1,reg2
  9951. imul y,reg2 to imul y,reg1,reg2 }
  9952. begin
  9953. taicpu(p).ops := 3;
  9954. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  9955. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  9956. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  9957. RemoveInstruction(hp1);
  9958. result:=true;
  9959. end;
  9960. end;
  9961. end;
  9962. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  9963. var
  9964. ThisLabel: TAsmLabel;
  9965. begin
  9966. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  9967. ThisLabel.decrefs;
  9968. taicpu(p).condition := C_None;
  9969. taicpu(p).opcode := A_RET;
  9970. taicpu(p).is_jmp := false;
  9971. taicpu(p).ops := taicpu(ret_p).ops;
  9972. case taicpu(ret_p).ops of
  9973. 0:
  9974. taicpu(p).clearop(0);
  9975. 1:
  9976. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  9977. else
  9978. internalerror(2016041301);
  9979. end;
  9980. { If the original label is now dead, it might turn out that the label
  9981. immediately follows p. As a result, everything beyond it, which will
  9982. be just some final register configuration and a RET instruction, is
  9983. now dead code. [Kit] }
  9984. { NOTE: This is much faster than introducing a OptPass2RET routine and
  9985. running RemoveDeadCodeAfterJump for each RET instruction, because
  9986. this optimisation rarely happens and most RETs appear at the end of
  9987. routines where there is nothing that can be stripped. [Kit] }
  9988. if not ThisLabel.is_used then
  9989. RemoveDeadCodeAfterJump(p);
  9990. end;
  9991. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  9992. var
  9993. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  9994. Unconditional, PotentialModified: Boolean;
  9995. OperPtr: POper;
  9996. NewRef: TReference;
  9997. InstrList: array of taicpu;
  9998. InstrMax, Index: Integer;
  9999. const
  10000. {$ifdef DEBUG_AOPTCPU}
  10001. SNoFlags: shortstring = ' so the flags aren''t modified';
  10002. {$else DEBUG_AOPTCPU}
  10003. SNoFlags = '';
  10004. {$endif DEBUG_AOPTCPU}
  10005. begin
  10006. Result:=false;
  10007. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  10008. begin
  10009. if MatchInstruction(hp1, A_TEST, [S_B]) and
  10010. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10011. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10012. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  10013. GetNextInstruction(hp1, hp2) and
  10014. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  10015. { Change from: To:
  10016. set(C) %reg j(~C) label
  10017. test %reg,%reg/cmp $0,%reg
  10018. je label
  10019. set(C) %reg j(C) label
  10020. test %reg,%reg/cmp $0,%reg
  10021. jne label
  10022. (Also do something similar with sete/setne instead of je/jne)
  10023. }
  10024. begin
  10025. { Before we do anything else, we need to check the instructions
  10026. in between SETcc and TEST to make sure they don't modify the
  10027. FLAGS register - if -O2 or under, there won't be any
  10028. instructions between SET and TEST }
  10029. TransferUsedRegs(TmpUsedRegs);
  10030. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10031. if (cs_opt_level3 in current_settings.optimizerswitches) then
  10032. begin
  10033. next := p;
  10034. SetLength(InstrList, 0);
  10035. InstrMax := -1;
  10036. PotentialModified := False;
  10037. { Make a note of every instruction that modifies the FLAGS
  10038. register }
  10039. while GetNextInstruction(next, next) and (next <> hp1) do
  10040. begin
  10041. if next.typ <> ait_instruction then
  10042. { GetNextInstructionUsingReg should have returned False }
  10043. InternalError(2021051701);
  10044. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  10045. begin
  10046. case taicpu(next).opcode of
  10047. A_SETcc,
  10048. A_CMOVcc,
  10049. A_Jcc:
  10050. begin
  10051. if PotentialModified then
  10052. { Not safe because the flags were modified earlier }
  10053. Exit
  10054. else
  10055. { Condition is the same as the initial SETcc, so this is safe
  10056. (don't add to instruction list though) }
  10057. Continue;
  10058. end;
  10059. A_ADD:
  10060. begin
  10061. if (taicpu(next).opsize = S_B) or
  10062. { LEA doesn't support 8-bit operands }
  10063. (taicpu(next).oper[1]^.typ <> top_reg) or
  10064. { Must write to a register }
  10065. (taicpu(next).oper[0]^.typ = top_ref) then
  10066. { Require a constant or a register }
  10067. Exit;
  10068. PotentialModified := True;
  10069. end;
  10070. A_SUB:
  10071. begin
  10072. if (taicpu(next).opsize = S_B) or
  10073. { LEA doesn't support 8-bit operands }
  10074. (taicpu(next).oper[1]^.typ <> top_reg) or
  10075. { Must write to a register }
  10076. (taicpu(next).oper[0]^.typ <> top_const) or
  10077. (taicpu(next).oper[0]^.val = $80000000) then
  10078. { Can't subtract a register with LEA - also
  10079. check that the value isn't -2^31, as this
  10080. can't be negated }
  10081. Exit;
  10082. PotentialModified := True;
  10083. end;
  10084. A_SAL,
  10085. A_SHL:
  10086. begin
  10087. if (taicpu(next).opsize = S_B) or
  10088. { LEA doesn't support 8-bit operands }
  10089. (taicpu(next).oper[1]^.typ <> top_reg) or
  10090. { Must write to a register }
  10091. (taicpu(next).oper[0]^.typ <> top_const) or
  10092. (taicpu(next).oper[0]^.val < 0) or
  10093. (taicpu(next).oper[0]^.val > 3) then
  10094. Exit;
  10095. PotentialModified := True;
  10096. end;
  10097. A_IMUL:
  10098. begin
  10099. if (taicpu(next).ops <> 3) or
  10100. (taicpu(next).oper[1]^.typ <> top_reg) or
  10101. { Must write to a register }
  10102. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  10103. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  10104. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  10105. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  10106. Exit
  10107. else
  10108. PotentialModified := True;
  10109. end;
  10110. else
  10111. { Don't know how to change this, so abort }
  10112. Exit;
  10113. end;
  10114. { Contains highest index (so instruction count - 1) }
  10115. Inc(InstrMax);
  10116. if InstrMax > High(InstrList) then
  10117. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  10118. InstrList[InstrMax] := taicpu(next);
  10119. end;
  10120. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  10121. end;
  10122. if not Assigned(next) or (next <> hp1) then
  10123. { It should be equal to hp1 }
  10124. InternalError(2021051702);
  10125. { Cycle through each instruction and check to see if we can
  10126. change them to versions that don't modify the flags }
  10127. if (InstrMax >= 0) then
  10128. begin
  10129. for Index := 0 to InstrMax do
  10130. case InstrList[Index].opcode of
  10131. A_ADD:
  10132. begin
  10133. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  10134. InstrList[Index].opcode := A_LEA;
  10135. reference_reset(NewRef, 1, []);
  10136. NewRef.base := InstrList[Index].oper[1]^.reg;
  10137. if InstrList[Index].oper[0]^.typ = top_reg then
  10138. begin
  10139. NewRef.index := InstrList[Index].oper[0]^.reg;
  10140. NewRef.scalefactor := 1;
  10141. end
  10142. else
  10143. NewRef.offset := InstrList[Index].oper[0]^.val;
  10144. InstrList[Index].loadref(0, NewRef);
  10145. end;
  10146. A_SUB:
  10147. begin
  10148. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  10149. InstrList[Index].opcode := A_LEA;
  10150. reference_reset(NewRef, 1, []);
  10151. NewRef.base := InstrList[Index].oper[1]^.reg;
  10152. NewRef.offset := -InstrList[Index].oper[0]^.val;
  10153. InstrList[Index].loadref(0, NewRef);
  10154. end;
  10155. A_SHL,
  10156. A_SAL:
  10157. begin
  10158. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  10159. InstrList[Index].opcode := A_LEA;
  10160. reference_reset(NewRef, 1, []);
  10161. NewRef.index := InstrList[Index].oper[1]^.reg;
  10162. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  10163. InstrList[Index].loadref(0, NewRef);
  10164. end;
  10165. A_IMUL:
  10166. begin
  10167. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  10168. InstrList[Index].opcode := A_LEA;
  10169. reference_reset(NewRef, 1, []);
  10170. NewRef.index := InstrList[Index].oper[1]^.reg;
  10171. case InstrList[Index].oper[0]^.val of
  10172. 2, 4, 8:
  10173. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  10174. else {3, 5 and 9}
  10175. begin
  10176. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  10177. NewRef.base := InstrList[Index].oper[1]^.reg;
  10178. end;
  10179. end;
  10180. InstrList[Index].loadref(0, NewRef);
  10181. end;
  10182. else
  10183. InternalError(2021051710);
  10184. end;
  10185. end;
  10186. { Mark the FLAGS register as used across this whole block }
  10187. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  10188. end;
  10189. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10190. JumpC := taicpu(hp2).condition;
  10191. Unconditional := False;
  10192. if conditions_equal(JumpC, C_E) then
  10193. SetC := inverse_cond(taicpu(p).condition)
  10194. else if conditions_equal(JumpC, C_NE) then
  10195. SetC := taicpu(p).condition
  10196. else
  10197. { We've got something weird here (and inefficent) }
  10198. begin
  10199. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  10200. SetC := C_NONE;
  10201. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  10202. if condition_in(C_AE, JumpC) then
  10203. Unconditional := True
  10204. else
  10205. { Not sure what to do with this jump - drop out }
  10206. Exit;
  10207. end;
  10208. RemoveInstruction(hp1);
  10209. if Unconditional then
  10210. MakeUnconditional(taicpu(hp2))
  10211. else
  10212. begin
  10213. if SetC = C_NONE then
  10214. InternalError(2018061402);
  10215. taicpu(hp2).SetCondition(SetC);
  10216. end;
  10217. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  10218. TmpUsedRegs }
  10219. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  10220. begin
  10221. RemoveCurrentp(p, hp2);
  10222. if taicpu(hp2).opcode = A_SETcc then
  10223. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  10224. else
  10225. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  10226. end
  10227. else
  10228. if taicpu(hp2).opcode = A_SETcc then
  10229. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  10230. else
  10231. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  10232. Result := True;
  10233. end
  10234. else if
  10235. { Make sure the instructions are adjacent }
  10236. (
  10237. not (cs_opt_level3 in current_settings.optimizerswitches) or
  10238. GetNextInstruction(p, hp1)
  10239. ) and
  10240. MatchInstruction(hp1, A_MOV, [S_B]) and
  10241. { Writing to memory is allowed }
  10242. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  10243. begin
  10244. {
  10245. Watch out for sequences such as:
  10246. set(c)b %regb
  10247. movb %regb,(ref)
  10248. movb $0,1(ref)
  10249. movb $0,2(ref)
  10250. movb $0,3(ref)
  10251. Much more efficient to turn it into:
  10252. movl $0,%regl
  10253. set(c)b %regb
  10254. movl %regl,(ref)
  10255. Or:
  10256. set(c)b %regb
  10257. movzbl %regb,%regl
  10258. movl %regl,(ref)
  10259. }
  10260. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  10261. GetNextInstruction(hp1, hp2) and
  10262. MatchInstruction(hp2, A_MOV, [S_B]) and
  10263. (taicpu(hp2).oper[1]^.typ = top_ref) and
  10264. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  10265. begin
  10266. { Don't do anything else except set Result to True }
  10267. end
  10268. else
  10269. begin
  10270. if taicpu(p).oper[0]^.typ = top_reg then
  10271. begin
  10272. TransferUsedRegs(TmpUsedRegs);
  10273. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10274. end;
  10275. { If it's not a register, it's a memory address }
  10276. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  10277. begin
  10278. { Even if the register is still in use, we can minimise the
  10279. pipeline stall by changing the MOV into another SETcc. }
  10280. taicpu(hp1).opcode := A_SETcc;
  10281. taicpu(hp1).condition := taicpu(p).condition;
  10282. if taicpu(hp1).oper[1]^.typ = top_ref then
  10283. begin
  10284. { Swapping the operand pointers like this is probably a
  10285. bit naughty, but it is far faster than using loadoper
  10286. to transfer the reference from oper[1] to oper[0] if
  10287. you take into account the extra procedure calls and
  10288. the memory allocation and deallocation required }
  10289. OperPtr := taicpu(hp1).oper[1];
  10290. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  10291. taicpu(hp1).oper[0] := OperPtr;
  10292. end
  10293. else
  10294. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  10295. taicpu(hp1).clearop(1);
  10296. taicpu(hp1).ops := 1;
  10297. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  10298. end
  10299. else
  10300. begin
  10301. if taicpu(hp1).oper[1]^.typ = top_reg then
  10302. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  10303. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  10304. RemoveInstruction(hp1);
  10305. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  10306. end
  10307. end;
  10308. Result := True;
  10309. end;
  10310. end;
  10311. end;
  10312. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  10313. var
  10314. hp1: tai;
  10315. Count: Integer;
  10316. OrigLabel: TAsmLabel;
  10317. begin
  10318. result := False;
  10319. { Sometimes, the optimisations below can permit this }
  10320. RemoveDeadCodeAfterJump(p);
  10321. 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
  10322. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  10323. begin
  10324. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10325. { Also a side-effect of optimisations }
  10326. if CollapseZeroDistJump(p, OrigLabel) then
  10327. begin
  10328. Result := True;
  10329. Exit;
  10330. end;
  10331. hp1 := GetLabelWithSym(OrigLabel);
  10332. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  10333. begin
  10334. if taicpu(hp1).opcode = A_RET then
  10335. begin
  10336. {
  10337. change
  10338. jmp .L1
  10339. ...
  10340. .L1:
  10341. ret
  10342. into
  10343. ret
  10344. }
  10345. begin
  10346. ConvertJumpToRET(p, hp1);
  10347. result:=true;
  10348. end;
  10349. end
  10350. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  10351. not (cs_opt_size in current_settings.optimizerswitches) and
  10352. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  10353. begin
  10354. Result := True;
  10355. Exit;
  10356. end;
  10357. end;
  10358. end;
  10359. end;
  10360. class function TX86AsmOptimizer.CanBeCMOV(p, cond_p: tai) : boolean;
  10361. begin
  10362. Result := assigned(p) and
  10363. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  10364. (taicpu(p).oper[1]^.typ = top_reg) and
  10365. (
  10366. (taicpu(p).oper[0]^.typ = top_reg) or
  10367. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  10368. it is not expected that this can cause a seg. violation }
  10369. (
  10370. (taicpu(p).oper[0]^.typ = top_ref) and
  10371. { TODO: Can we detect which references become constants at this
  10372. stage so we don't have to do a blanket ban? }
  10373. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  10374. (
  10375. IsRefSafe(taicpu(p).oper[0]^.ref) or
  10376. (
  10377. { If the reference also appears in the condition, then we know it's safe, otherwise
  10378. any kind of access violation would have occurred already }
  10379. Assigned(cond_p) and
  10380. { Make sure the sizes match too so we're reading and writing the same number of bytes }
  10381. (cond_p.typ = ait_instruction) and
  10382. (taicpu(cond_p).opsize = taicpu(p).opsize) and
  10383. { Just consider 2-operand comparison instructions for now to be safe }
  10384. (taicpu(cond_p).ops = 2) and
  10385. (
  10386. ((taicpu(cond_p).oper[1]^.typ = top_ref) and RefsEqual(taicpu(cond_p).oper[1]^.ref^, taicpu(p).oper[0]^.ref^)) or
  10387. (
  10388. (taicpu(cond_p).oper[0]^.typ = top_ref) and
  10389. { Don't risk identical registers but different offsets, as we may have constructs
  10390. such as buffer streams with things like length fields that indicate whether
  10391. any more data follows. And there are probably some contrived examples where
  10392. writing to offsets behind the one being read also lead to access violations }
  10393. RefsEqual(taicpu(cond_p).oper[0]^.ref^, taicpu(p).oper[0]^.ref^) and
  10394. (
  10395. { Check that we're not modifying a register that appears in the reference }
  10396. (InsProp[taicpu(cond_p).opcode].Ch * [Ch_Mop2, Ch_RWop2, Ch_Wop2] = []) or
  10397. (taicpu(cond_p).oper[1]^.typ <> top_reg) or
  10398. not RegInRef(taicpu(cond_p).oper[1]^.reg, taicpu(cond_p).oper[0]^.ref^)
  10399. )
  10400. )
  10401. )
  10402. )
  10403. )
  10404. )
  10405. );
  10406. end;
  10407. class procedure TX86AsmOptimizer.UpdateIntRegsNoDealloc(var AUsedRegs: TAllUsedRegs; p: Tai);
  10408. begin
  10409. { Update integer registers, ignoring deallocations }
  10410. repeat
  10411. while assigned(p) and
  10412. ((p.typ in (SkipInstr - [ait_RegAlloc])) or
  10413. (p.typ = ait_label) or
  10414. ((p.typ = ait_marker) and
  10415. (tai_Marker(p).Kind in [mark_AsmBlockEnd,mark_NoLineInfoStart,mark_NoLineInfoEnd]))) do
  10416. p := tai(p.next);
  10417. while assigned(p) and
  10418. (p.typ=ait_RegAlloc) Do
  10419. begin
  10420. if (getregtype(tai_regalloc(p).reg) = R_INTREGISTER) then
  10421. begin
  10422. case tai_regalloc(p).ratype of
  10423. ra_alloc :
  10424. IncludeRegInUsedRegs(tai_regalloc(p).reg, AUsedRegs);
  10425. else
  10426. ;
  10427. end;
  10428. end;
  10429. p := tai(p.next);
  10430. end;
  10431. until not(assigned(p)) or
  10432. (not(p.typ in SkipInstr) and
  10433. not((p.typ = ait_label) and
  10434. labelCanBeSkipped(tai_label(p))));
  10435. end;
  10436. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  10437. var
  10438. hp1,hp2: tai;
  10439. carryadd_opcode : TAsmOp;
  10440. symbol: TAsmSymbol;
  10441. increg, tmpreg: TRegister;
  10442. {$ifndef i8086}
  10443. { Code and variables specific to CMOV optimisations }
  10444. hp3,hp4,hp5,
  10445. hp_stop, hp_lblxxx, hp_lblyyy, hpmov1,hpmov2, hp_prev, hp_flagalloc, hp_prev2, hp_new, hp_jump: tai;
  10446. l, c, w, x : Longint;
  10447. condition, second_condition : TAsmCond;
  10448. FoundMatchingJump, RegMatch: Boolean;
  10449. RegWrites: array[0..MAX_CMOV_INSTRUCTIONS*2 - 1] of TRegister;
  10450. ConstRegs: array[0..MAX_CMOV_REGISTERS - 1] of TRegister;
  10451. ConstVals: array[0..MAX_CMOV_REGISTERS - 1] of TCGInt;
  10452. { Tries to convert a mov const,%reg instruction into a CMOV by reserving a
  10453. new register to store the constant }
  10454. function TryCMOVConst(p, search_start_p, stop_search_p: tai; var StoredCount: LongInt; var CMOVCount: LongInt): Boolean;
  10455. var
  10456. RegSize: TSubRegister;
  10457. CurrentVal: TCGInt;
  10458. NewReg: TRegister;
  10459. X: ShortInt;
  10460. begin
  10461. Result := False;
  10462. if not MatchOpType(taicpu(p), top_const, top_reg) then
  10463. Exit;
  10464. if StoredCount >= MAX_CMOV_REGISTERS then
  10465. { Arrays are full }
  10466. Exit;
  10467. { Remember that CMOV can't encode 8-bit registers }
  10468. case taicpu(p).opsize of
  10469. S_W:
  10470. RegSize := R_SUBW;
  10471. S_L:
  10472. RegSize := R_SUBD;
  10473. S_Q:
  10474. RegSize := R_SUBQ;
  10475. else
  10476. InternalError(2021100401);
  10477. end;
  10478. { See if the value has already been reserved for another CMOV instruction }
  10479. CurrentVal := taicpu(p).oper[0]^.val;
  10480. for X := 0 to StoredCount - 1 do
  10481. if ConstVals[X] = CurrentVal then
  10482. begin
  10483. ConstRegs[StoredCount] := ConstRegs[X];
  10484. ConstVals[StoredCount] := CurrentVal;
  10485. Result := True;
  10486. Inc(StoredCount);
  10487. { Don't increase CMOVCount this time, since we're re-using a register }
  10488. Exit;
  10489. end;
  10490. NewReg := GetIntRegisterBetween(RegSize, TmpUsedRegs, search_start_p, stop_search_p, True);
  10491. if NewReg = NR_NO then
  10492. { No free registers }
  10493. Exit;
  10494. { Reserve the register so subsequent TryCMOVConst calls don't all end
  10495. up vying for the same register }
  10496. IncludeRegInUsedRegs(NewReg, TmpUsedRegs);
  10497. ConstRegs[StoredCount] := NewReg;
  10498. ConstVals[StoredCount] := CurrentVal;
  10499. Inc(StoredCount);
  10500. { Increment the CMOV count variable from OptPass2JCC, since the extra
  10501. MOV required adds complexity and will cause diminishing returns
  10502. sooner than normal. This is more of an approximate weighting than
  10503. anything else. }
  10504. Inc(CMOVCount);
  10505. Result := True;
  10506. end;
  10507. {$endif i8086}
  10508. begin
  10509. result:=false;
  10510. if GetNextInstruction(p,hp1) then
  10511. begin
  10512. if (hp1.typ=ait_label) then
  10513. begin
  10514. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  10515. Exit;
  10516. end
  10517. else if (hp1.typ<>ait_instruction) then
  10518. Exit;
  10519. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10520. if (
  10521. (
  10522. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  10523. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  10524. (Taicpu(hp1).oper[0]^.val=1)
  10525. ) or
  10526. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10527. ) and
  10528. GetNextInstruction(hp1,hp2) and
  10529. SkipAligns(hp2, hp2) and
  10530. (hp2.typ = ait_label) and
  10531. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10532. { jb @@1 cmc
  10533. inc/dec operand --> adc/sbb operand,0
  10534. @@1:
  10535. ... and ...
  10536. jnb @@1
  10537. inc/dec operand --> adc/sbb operand,0
  10538. @@1: }
  10539. begin
  10540. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10541. begin
  10542. case taicpu(hp1).opcode of
  10543. A_INC,
  10544. A_ADD:
  10545. carryadd_opcode:=A_ADC;
  10546. A_DEC,
  10547. A_SUB:
  10548. carryadd_opcode:=A_SBB;
  10549. else
  10550. InternalError(2021011001);
  10551. end;
  10552. Taicpu(p).clearop(0);
  10553. Taicpu(p).ops:=0;
  10554. Taicpu(p).is_jmp:=false;
  10555. Taicpu(p).opcode:=A_CMC;
  10556. Taicpu(p).condition:=C_NONE;
  10557. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10558. Taicpu(hp1).ops:=2;
  10559. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10560. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10561. else
  10562. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10563. Taicpu(hp1).loadconst(0,0);
  10564. Taicpu(hp1).opcode:=carryadd_opcode;
  10565. result:=true;
  10566. exit;
  10567. end
  10568. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10569. begin
  10570. case taicpu(hp1).opcode of
  10571. A_INC,
  10572. A_ADD:
  10573. carryadd_opcode:=A_ADC;
  10574. A_DEC,
  10575. A_SUB:
  10576. carryadd_opcode:=A_SBB;
  10577. else
  10578. InternalError(2021011002);
  10579. end;
  10580. Taicpu(hp1).ops:=2;
  10581. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10582. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10583. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10584. else
  10585. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10586. Taicpu(hp1).loadconst(0,0);
  10587. Taicpu(hp1).opcode:=carryadd_opcode;
  10588. RemoveCurrentP(p, hp1);
  10589. result:=true;
  10590. exit;
  10591. end
  10592. {
  10593. jcc @@1 setcc tmpreg
  10594. inc/dec/add/sub operand -> (movzx tmpreg)
  10595. @@1: add/sub tmpreg,operand
  10596. While this increases code size slightly, it makes the code much faster if the
  10597. jump is unpredictable
  10598. }
  10599. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10600. begin
  10601. { search for an available register which is volatile }
  10602. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10603. if increg <> NR_NO then
  10604. begin
  10605. { We don't need to check if tmpreg is in hp1 or not, because
  10606. it will be marked as in use at p (if not, this is
  10607. indictive of a compiler bug). }
  10608. TAsmLabel(symbol).decrefs;
  10609. Taicpu(p).clearop(0);
  10610. Taicpu(p).ops:=1;
  10611. Taicpu(p).is_jmp:=false;
  10612. Taicpu(p).opcode:=A_SETcc;
  10613. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10614. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10615. Taicpu(p).loadreg(0,increg);
  10616. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10617. begin
  10618. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10619. R_SUBW:
  10620. begin
  10621. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10622. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10623. end;
  10624. R_SUBD:
  10625. begin
  10626. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10627. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10628. end;
  10629. {$ifdef x86_64}
  10630. R_SUBQ:
  10631. begin
  10632. { MOVZX doesn't have a 64-bit variant, because
  10633. the 32-bit version implicitly zeroes the
  10634. upper 32-bits of the destination register }
  10635. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10636. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10637. setsubreg(tmpreg, R_SUBQ);
  10638. end;
  10639. {$endif x86_64}
  10640. else
  10641. Internalerror(2020030601);
  10642. end;
  10643. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10644. asml.InsertAfter(hp2,p);
  10645. end
  10646. else
  10647. tmpreg := increg;
  10648. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10649. begin
  10650. Taicpu(hp1).ops:=2;
  10651. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10652. end;
  10653. Taicpu(hp1).loadreg(0,tmpreg);
  10654. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10655. Result := True;
  10656. { p is no longer a Jcc instruction, so exit }
  10657. Exit;
  10658. end;
  10659. end;
  10660. end;
  10661. { Detect the following:
  10662. jmp<cond> @Lbl1
  10663. jmp @Lbl2
  10664. ...
  10665. @Lbl1:
  10666. ret
  10667. Change to:
  10668. jmp<inv_cond> @Lbl2
  10669. ret
  10670. }
  10671. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10672. begin
  10673. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10674. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10675. MatchInstruction(hp2,A_RET,[S_NO]) then
  10676. begin
  10677. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10678. { Change label address to that of the unconditional jump }
  10679. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10680. TAsmLabel(symbol).DecRefs;
  10681. taicpu(hp1).opcode := A_RET;
  10682. taicpu(hp1).is_jmp := false;
  10683. taicpu(hp1).ops := taicpu(hp2).ops;
  10684. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10685. case taicpu(hp2).ops of
  10686. 0:
  10687. taicpu(hp1).clearop(0);
  10688. 1:
  10689. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10690. else
  10691. internalerror(2016041302);
  10692. end;
  10693. end;
  10694. {$ifndef i8086}
  10695. end
  10696. {
  10697. convert
  10698. j<c> .L1
  10699. mov 1,reg
  10700. jmp .L2
  10701. .L1
  10702. mov 0,reg
  10703. .L2
  10704. into
  10705. mov 0,reg
  10706. set<not(c)> reg
  10707. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10708. would destroy the flag contents
  10709. }
  10710. else if MatchInstruction(hp1,A_MOV,[]) and
  10711. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10712. {$ifdef i386}
  10713. (
  10714. { Under i386, ESI, EDI, EBP and ESP
  10715. don't have an 8-bit representation }
  10716. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10717. ) and
  10718. {$endif i386}
  10719. (taicpu(hp1).oper[0]^.val=1) and
  10720. GetNextInstruction(hp1,hp2) and
  10721. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10722. GetNextInstruction(hp2,hp3) and
  10723. { skip align }
  10724. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10725. (hp3.typ=ait_label) and
  10726. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10727. (tai_label(hp3).labsym.getrefs=1) and
  10728. GetNextInstruction(hp3,hp4) and
  10729. MatchInstruction(hp4,A_MOV,[]) and
  10730. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10731. (taicpu(hp4).oper[0]^.val=0) and
  10732. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10733. GetNextInstruction(hp4,hp5) and
  10734. (hp5.typ=ait_label) and
  10735. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10736. (tai_label(hp5).labsym.getrefs=1) then
  10737. begin
  10738. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10739. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10740. { remove last label }
  10741. RemoveInstruction(hp5);
  10742. { remove second label }
  10743. RemoveInstruction(hp3);
  10744. { if align is present remove it }
  10745. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10746. RemoveInstruction(hp3);
  10747. { remove jmp }
  10748. RemoveInstruction(hp2);
  10749. if taicpu(hp1).opsize=S_B then
  10750. RemoveInstruction(hp1)
  10751. else
  10752. taicpu(hp1).loadconst(0,0);
  10753. taicpu(hp4).opcode:=A_SETcc;
  10754. taicpu(hp4).opsize:=S_B;
  10755. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10756. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10757. taicpu(hp4).opercnt:=1;
  10758. taicpu(hp4).ops:=1;
  10759. taicpu(hp4).freeop(1);
  10760. RemoveCurrentP(p);
  10761. Result:=true;
  10762. exit;
  10763. end
  10764. else if (CPUX86_HAS_CMOV in cpu_capabilities[current_settings.optimizecputype]) and
  10765. MatchInstruction(hp1,A_MOV,[S_W,S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  10766. begin
  10767. { check for
  10768. jCC xxx
  10769. <several movs>
  10770. xxx:
  10771. Also spot:
  10772. Jcc xxx
  10773. <several movs>
  10774. jmp xxx
  10775. Change to:
  10776. <several cmovs with inverted condition>
  10777. jmp xxx (only for the 2nd case)
  10778. }
  10779. hp2 := p;
  10780. hp_lblxxx := hp1;
  10781. hp_flagalloc := nil;
  10782. hp_stop := nil;
  10783. FoundMatchingJump := False;
  10784. { Remember the first instruction in the first block of MOVs }
  10785. hpmov1 := hp1;
  10786. TransferUsedRegs(TmpUsedRegs);
  10787. while assigned(hp_lblxxx) and
  10788. { stop on labels }
  10789. (hp_lblxxx.typ <> ait_label) do
  10790. begin
  10791. { Keep track of all integer registers that are used }
  10792. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  10793. if hp_lblxxx.typ = ait_instruction then
  10794. begin
  10795. if (taicpu(hp_lblxxx).opcode = A_JMP) and
  10796. IsJumpToLabel(taicpu(hp_lblxxx)) then
  10797. begin
  10798. hp_stop := hp_lblxxx;
  10799. if (TAsmLabel(taicpu(hp_lblxxx).oper[0]^.ref^.symbol) = symbol) then
  10800. begin
  10801. { We found Jcc xxx; <several movs>; Jmp xxx }
  10802. FoundMatchingJump := True;
  10803. Break;
  10804. end;
  10805. { If it's not the jump we're looking for, it's
  10806. possibly the "if..else" variant }
  10807. end
  10808. { Check to see if we have a valid MOV instruction instead }
  10809. else if (taicpu(hp_lblxxx).opcode <> A_MOV) or
  10810. not (taicpu(hp_lblxxx).opsize in [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  10811. Break
  10812. else
  10813. { This will be a valid MOV }
  10814. hp_stop := hp_lblxxx;
  10815. end;
  10816. hp2 := hp_lblxxx;
  10817. GetNextInstruction(hp_lblxxx, hp_lblxxx);
  10818. end;
  10819. { Just make sure the last MOV is included if there's no jump }
  10820. if (hp_lblxxx.typ = ait_label) and MatchInstruction(hp_stop, A_MOV, []) then
  10821. hp_stop := hp_lblxxx;
  10822. { Note, the logic behind using hp_stop over hp_lblxxx in the
  10823. range for TryCMOVConst is so GetIntRegisterBetween doesn't
  10824. fail when it reaches a JMP instruction in the "jcc xxx; movs;
  10825. jmp yyy; xxx:; movs; yyy:" variation }
  10826. if assigned(hp_lblxxx) and
  10827. (
  10828. { If we found JMP xxx, we don't actually need a label
  10829. (hp_lblxxx is the JMP instruction instead) }
  10830. FoundMatchingJump or
  10831. { Make sure we actually have the right label }
  10832. FindLabel(TAsmLabel(symbol), hp_lblxxx)
  10833. ) then
  10834. begin
  10835. { Use TmpUsedRegs to track registers that we reserve }
  10836. { When allocating temporary registers, try to look one
  10837. instruction back, as defining them before a CMP or TEST
  10838. instruction will be faster, and also avoid picking a
  10839. register that was only just deallocated }
  10840. if GetLastInstruction(p, hp_prev) and
  10841. MatchInstruction(hp_prev, [A_CMP, A_TEST, A_BSR, A_BSF, A_COMISS, A_COMISD, A_UCOMISS, A_UCOMISD, A_VCOMISS, A_VCOMISD, A_VUCOMISS, A_VUCOMISD], []) then
  10842. begin
  10843. { Mark all the registers in the comparison as 'in use', even if they've just been deallocated }
  10844. for l := 0 to 1 do
  10845. with taicpu(hp_prev).oper[l]^ do
  10846. case typ of
  10847. top_reg:
  10848. if getregtype(reg) = R_INTREGISTER then
  10849. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  10850. top_ref:
  10851. begin
  10852. if
  10853. {$ifdef x86_64}
  10854. (ref^.base <> NR_RIP) and
  10855. {$endif x86_64}
  10856. (ref^.base <> NR_NO) then
  10857. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  10858. if (ref^.index <> NR_NO) then
  10859. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  10860. end
  10861. else
  10862. ;
  10863. end;
  10864. { When inserting instructions before hp_prev, try to insert
  10865. them before the allocation of the FLAGS register }
  10866. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(hp_prev.Previous)), hp_flagalloc) then
  10867. { If not found, set it equal to hp_prev so it's something sensible }
  10868. hp_flagalloc := hp_prev;
  10869. hp_prev2 := nil;
  10870. { When dealing with a comparison against zero, take
  10871. note of the instruction before it to see if we can
  10872. move instructions further back in order to benefit
  10873. PostPeepholeOptTestOr.
  10874. }
  10875. if (
  10876. (
  10877. (taicpu(hp_prev).opcode = A_CMP) and
  10878. MatchOperand(taicpu(hp_prev).oper[0]^, 0)
  10879. ) or
  10880. (
  10881. (taicpu(hp_prev).opcode = A_TEST) and
  10882. (
  10883. OpsEqual(taicpu(hp_prev).oper[0]^, taicpu(hp_prev).oper[1]^) or
  10884. MatchOperand(taicpu(hp_prev).oper[0]^, -1)
  10885. )
  10886. )
  10887. ) and
  10888. GetLastInstruction(hp_prev, hp_prev2) then
  10889. begin
  10890. if (hp_prev2.typ = ait_instruction) and
  10891. { These instructions set the zero flag if the result is zero }
  10892. MatchInstruction(hp_prev2, [A_ADD, A_SUB, A_OR, A_XOR, A_AND, A_POPCNT, A_LZCNT], []) then
  10893. begin
  10894. { Also mark all the registers in this previous instruction
  10895. as 'in use', even if they've just been deallocated }
  10896. for l := 0 to 1 do
  10897. with taicpu(hp_prev2).oper[l]^ do
  10898. case typ of
  10899. top_reg:
  10900. if getregtype(reg) = R_INTREGISTER then
  10901. IncludeRegInUsedRegs(reg, TmpUsedRegs);
  10902. top_ref:
  10903. begin
  10904. if
  10905. {$ifdef x86_64}
  10906. (ref^.base <> NR_RIP) and
  10907. {$endif x86_64}
  10908. (ref^.base <> NR_NO) then
  10909. IncludeRegInUsedRegs(ref^.base, TmpUsedRegs);
  10910. if (ref^.index <> NR_NO) then
  10911. IncludeRegInUsedRegs(ref^.index, TmpUsedRegs);
  10912. end
  10913. else
  10914. ;
  10915. end;
  10916. end
  10917. else
  10918. { Unsuitable instruction }
  10919. hp_prev2 := nil;
  10920. end;
  10921. end
  10922. else
  10923. begin
  10924. hp_prev := p;
  10925. { When inserting instructions before hp_prev, try to insert
  10926. them before the allocation of the FLAGS register }
  10927. if not SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp_flagalloc) then
  10928. { If not found, set it equal to p so it's something sensible }
  10929. hp_flagalloc := p;
  10930. hp_prev2 := nil;
  10931. end;
  10932. l := 0;
  10933. c := 0;
  10934. { Initialise RegWrites, ConstRegs and ConstVals }
  10935. FillChar(RegWrites[0], MAX_CMOV_INSTRUCTIONS * 2 * SizeOf(TRegister), 0);
  10936. FillChar(ConstRegs[0], MAX_CMOV_REGISTERS * SizeOf(TRegister), 0);
  10937. FillChar(ConstVals[0], MAX_CMOV_REGISTERS * SizeOf(TCGInt), 0);
  10938. while assigned(hp1) and
  10939. { Stop on the label we found }
  10940. (hp1 <> hp_lblxxx) do
  10941. begin
  10942. case hp1.typ of
  10943. ait_instruction:
  10944. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  10945. begin
  10946. if CanBeCMOV(hp1, hp_prev) then
  10947. Inc(l)
  10948. else if not (cs_opt_size in current_settings.optimizerswitches) and
  10949. { CMOV with constants grows the code size }
  10950. TryCMOVConst(hp1, hp_prev, hp_stop, c, l) then
  10951. begin
  10952. { Register was reserved by TryCMOVConst and
  10953. stored on ConstRegs[c] }
  10954. end
  10955. else
  10956. Break;
  10957. end
  10958. else
  10959. Break;
  10960. else
  10961. ;
  10962. end;
  10963. GetNextInstruction(hp1,hp1);
  10964. end;
  10965. if (hp1 = hp_lblxxx) then
  10966. begin
  10967. if (l <= MAX_CMOV_INSTRUCTIONS) and (l > 0) then
  10968. begin
  10969. { Repurpose TmpUsedRegs to mark registers that we've defined }
  10970. TmpUsedRegs[R_INTREGISTER].Clear;
  10971. x := 0;
  10972. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblxxx, UsedRegs);
  10973. condition := inverse_cond(taicpu(p).condition);
  10974. UpdateUsedRegs(tai(p.next));
  10975. hp1 := hpmov1;
  10976. repeat
  10977. if not Assigned(hp1) then
  10978. InternalError(2018062900);
  10979. if (hp1.typ = ait_instruction) then
  10980. begin
  10981. { Extra safeguard }
  10982. if (taicpu(hp1).opcode <> A_MOV) then
  10983. InternalError(2018062901);
  10984. if taicpu(hp1).oper[0]^.typ = top_const then
  10985. begin
  10986. if x >= MAX_CMOV_REGISTERS then
  10987. InternalError(2021100410);
  10988. { If it's in TmpUsedRegs, then this register
  10989. is being used more than once and hence has
  10990. already had its value defined (it gets
  10991. added to UsedRegs through AllocRegBetween
  10992. below) }
  10993. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  10994. begin
  10995. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  10996. taicpu(hp_new).fileinfo := taicpu(hp_prev).fileinfo;
  10997. asml.InsertBefore(hp_new, hp_flagalloc);
  10998. if Assigned(hp_prev2) then
  10999. TrySwapMovOp(hp_prev2, hp_new);
  11000. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11001. end
  11002. else
  11003. { We just need an instruction between hp_prev and hp1
  11004. where we know the register is marked as in use }
  11005. hp_new := hpmov1;
  11006. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11007. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11008. Inc(x);
  11009. end;
  11010. taicpu(hp1).opcode := A_CMOVcc;
  11011. taicpu(hp1).condition := condition;
  11012. end;
  11013. UpdateUsedRegs(tai(hp1.next));
  11014. GetNextInstruction(hp1, hp1);
  11015. until (hp1 = hp_lblxxx);
  11016. hp2 := hp_lblxxx;
  11017. repeat
  11018. if not Assigned(hp2) then
  11019. InternalError(2018062910);
  11020. case hp2.typ of
  11021. ait_label:
  11022. { What we expected - break out of the loop (it won't be a dead label at the top of
  11023. a cluster because that was optimised at an earlier stage) }
  11024. Break;
  11025. ait_align:
  11026. { Go to the next entry until a label is found (may be multiple aligns before it) }
  11027. begin
  11028. hp2 := tai(hp2.Next);
  11029. Continue;
  11030. end;
  11031. ait_instruction:
  11032. begin
  11033. if taicpu(hp2).opcode<>A_JMP then
  11034. InternalError(2018062912);
  11035. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  11036. Break;
  11037. end
  11038. else
  11039. begin
  11040. { Might be a comment or temporary allocation entry }
  11041. if not (hp2.typ in SkipInstr) then
  11042. InternalError(2018062911);
  11043. hp2 := tai(hp2.Next);
  11044. Continue;
  11045. end;
  11046. end;
  11047. until False;
  11048. { Now we can safely decrement the reference count }
  11049. tasmlabel(symbol).decrefs;
  11050. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  11051. { Remove the original jump }
  11052. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  11053. if hp2.typ=ait_instruction then
  11054. begin
  11055. p := hp2;
  11056. Result := True;
  11057. end
  11058. else
  11059. begin
  11060. UpdateUsedRegs(tai(hp2.next));
  11061. Result := GetNextInstruction(hp2, p); { Instruction after the label }
  11062. { Remove the label if this is its final reference }
  11063. if (tasmlabel(symbol).getrefs=0) then
  11064. begin
  11065. { Make sure the aligns get stripped too }
  11066. hp1 := tai(hp_lblxxx.Previous);
  11067. while Assigned(hp1) and (hp1.typ = ait_align) do
  11068. begin
  11069. hp_lblxxx := hp1;
  11070. hp1 := tai(hp_lblxxx.Previous);
  11071. end;
  11072. StripLabelFast(hp_lblxxx);
  11073. end;
  11074. end;
  11075. Exit;
  11076. end;
  11077. end
  11078. else if assigned(hp_lblxxx) and
  11079. { check further for
  11080. jCC xxx
  11081. <several movs 1>
  11082. jmp yyy
  11083. xxx:
  11084. <several movs 2>
  11085. yyy:
  11086. }
  11087. (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11088. { hp1 should be pointing to jmp yyy }
  11089. MatchInstruction(hp1, A_JMP, []) and
  11090. { real label and jump, no further references to the
  11091. label are allowed }
  11092. (TAsmLabel(symbol).getrefs=1) and
  11093. FindLabel(TAsmLabel(symbol), hp_lblxxx) then
  11094. begin
  11095. hp_jump := hp1;
  11096. { Don't set c to zero }
  11097. l := 0;
  11098. w := 0;
  11099. GetNextInstruction(hp_lblxxx, hpmov2);
  11100. hp2 := hp_lblxxx;
  11101. hp_lblyyy := hpmov2;
  11102. while assigned(hp_lblyyy) and
  11103. { stop on labels }
  11104. (hp_lblyyy.typ <> ait_label) do
  11105. begin
  11106. { Keep track of all integer registers that are used }
  11107. UpdateIntRegsNoDealloc(TmpUsedRegs, tai(hp2.Next));
  11108. if not MatchInstruction(hp_lblyyy, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11109. Break;
  11110. hp2 := hp_lblyyy;
  11111. GetNextInstruction(hp_lblyyy, hp_lblyyy);
  11112. end;
  11113. { Analyse the second batch of MOVs to see if the setup is valid }
  11114. hp1 := hpmov2;
  11115. while assigned(hp1) and
  11116. (hp1 <> hp_lblyyy) do
  11117. begin
  11118. case hp1.typ of
  11119. ait_instruction:
  11120. if MatchInstruction(hp1, A_MOV, [S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  11121. begin
  11122. if CanBeCMOV(hp1, hp_prev) then
  11123. Inc(l)
  11124. else if not (cs_opt_size in current_settings.optimizerswitches)
  11125. { CMOV with constants grows the code size }
  11126. and TryCMOVConst(hp1, hpmov2, hp_lblyyy, c, l) then
  11127. begin
  11128. { Register was reserved by TryCMOVConst and
  11129. stored on ConstRegs[c] }
  11130. end
  11131. else
  11132. Break;
  11133. end
  11134. else
  11135. Break;
  11136. else
  11137. ;
  11138. end;
  11139. GetNextInstruction(hp1,hp1);
  11140. end;
  11141. { Repurpose TmpUsedRegs to mark registers that we've defined }
  11142. TmpUsedRegs[R_INTREGISTER].Clear;
  11143. if (l <= MAX_CMOV_INSTRUCTIONS - 1) and
  11144. (hp1 = hp_lblyyy) and
  11145. FindLabel(TAsmLabel(taicpu(hp_jump).oper[0]^.ref^.symbol), hp_lblyyy) then
  11146. begin
  11147. AllocRegBetween(NR_DEFAULTFLAGS, p, hp_lblyyy, UsedRegs);
  11148. second_condition := taicpu(p).condition;
  11149. condition := inverse_cond(taicpu(p).condition);
  11150. UpdateUsedRegs(tai(p.next));
  11151. { Scan through the first set of MOVs to update UsedRegs,
  11152. but don't process them yet }
  11153. hp1 := hpmov1;
  11154. repeat
  11155. if not Assigned(hp1) then
  11156. InternalError(2018062901);
  11157. UpdateUsedRegs(tai(hp1.next));
  11158. GetNextInstruction(hp1, hp1);
  11159. until (hp1 = hp_lblxxx);
  11160. UpdateUsedRegs(tai(hp_lblxxx.next));
  11161. { Process the second set of MOVs first,
  11162. because if a destination register is
  11163. shared between the first and second MOV
  11164. sets, it is more efficient to turn the
  11165. first one into a MOV instruction and place
  11166. it before the CMP if possible, but we
  11167. won't know which registers are shared
  11168. until we've processed at least one list,
  11169. so we might as well make it the second
  11170. one since that won't be modified again. }
  11171. hp1 := hpmov2;
  11172. repeat
  11173. if not Assigned(hp1) then
  11174. InternalError(2018062902);
  11175. if (hp1.typ = ait_instruction) then
  11176. begin
  11177. { Extra safeguard }
  11178. if (taicpu(hp1).opcode <> A_MOV) then
  11179. InternalError(2018062903);
  11180. if taicpu(hp1).oper[0]^.typ = top_const then
  11181. begin
  11182. RegMatch := False;
  11183. for x := 0 to c - 1 do
  11184. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) then
  11185. begin
  11186. RegMatch := True;
  11187. { If it's in TmpUsedRegs, then this register
  11188. is being used more than once and hence has
  11189. already had its value defined (it gets
  11190. added to UsedRegs through AllocRegBetween
  11191. below) }
  11192. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11193. begin
  11194. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11195. asml.InsertBefore(hp_new, hp_flagalloc);
  11196. if Assigned(hp_prev2) then
  11197. TrySwapMovOp(hp_prev2, hp_new);
  11198. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11199. end
  11200. else
  11201. { We just need an instruction between hp_prev and hp1
  11202. where we know the register is marked as in use }
  11203. hp_new := hpmov2;
  11204. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11205. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11206. Break;
  11207. end;
  11208. if not RegMatch then
  11209. InternalError(2021100411);
  11210. end;
  11211. taicpu(hp1).opcode := A_CMOVcc;
  11212. taicpu(hp1).condition := second_condition;
  11213. { Store these writes to search for
  11214. duplicates later on }
  11215. RegWrites[w] := taicpu(hp1).oper[1]^.reg;
  11216. Inc(w);
  11217. end;
  11218. UpdateUsedRegs(tai(hp1.next));
  11219. GetNextInstruction(hp1, hp1);
  11220. until (hp1 = hp_lblyyy);
  11221. { Now do the first set of MOVs }
  11222. hp1 := hpmov1;
  11223. repeat
  11224. if not Assigned(hp1) then
  11225. InternalError(2018062904);
  11226. if (hp1.typ = ait_instruction) then
  11227. begin
  11228. RegMatch := False;
  11229. { Extra safeguard }
  11230. if (taicpu(hp1).opcode <> A_MOV) then
  11231. InternalError(2018062905);
  11232. { Search through the RegWrites list to see
  11233. if there are any opposing CMOV pairs that
  11234. write to the same register }
  11235. for x := 0 to w - 1 do
  11236. if (RegWrites[x] = taicpu(hp1).oper[1]^.reg) then
  11237. begin
  11238. { We have a match. Keep this as a MOV }
  11239. { Move ahead in preparation }
  11240. GetNextInstruction(hp1, hp1);
  11241. RegMatch := True;
  11242. Break;
  11243. end;
  11244. if RegMatch then
  11245. Continue;
  11246. if taicpu(hp1).oper[0]^.typ = top_const then
  11247. begin
  11248. RegMatch := False;
  11249. for x := 0 to c - 1 do
  11250. if (ConstVals[x] = taicpu(hp1).oper[0]^.val) then
  11251. begin
  11252. RegMatch := True;
  11253. { If it's in TmpUsedRegs, then this register
  11254. is being used more than once and hence has
  11255. already had its value defined (it gets
  11256. added to UsedRegs through AllocRegBetween
  11257. below) }
  11258. if not TmpUsedRegs[R_INTREGISTER].IsUsed(ConstRegs[x]) then
  11259. begin
  11260. hp_new := taicpu.op_const_reg(A_MOV, taicpu(hp1).opsize, taicpu(hp1).oper[0]^.val, ConstRegs[x]);
  11261. asml.InsertBefore(hp_new, hp_flagalloc);
  11262. if Assigned(hp_prev2) then
  11263. TrySwapMovOp(hp_prev2, hp_new);
  11264. IncludeRegInUsedRegs(ConstRegs[x], TmpUsedRegs);
  11265. end
  11266. else
  11267. { We just need an instruction between hp_prev and hp1
  11268. where we know the register is marked as in use }
  11269. hp_new := hpmov1;
  11270. AllocRegBetween(ConstRegs[x], hp_new, hp1, UsedRegs);
  11271. taicpu(hp1).loadreg(0, ConstRegs[x]);
  11272. Break;
  11273. end;
  11274. if not RegMatch then
  11275. InternalError(2021100412);
  11276. end;
  11277. taicpu(hp1).opcode := A_CMOVcc;
  11278. taicpu(hp1).condition := condition;
  11279. end;
  11280. GetNextInstruction(hp1, hp1);
  11281. until (hp1 = hp_jump); { Stop at the jump, not lbl xxx }
  11282. UpdateUsedRegs(tai(hp_jump.next));
  11283. UpdateUsedRegs(tai(hp_lblyyy.next));
  11284. { Get first instruction after label }
  11285. hp1 := p;
  11286. GetNextInstruction(hp_lblyyy, p);
  11287. { Don't dereference yet, as doing so will cause
  11288. GetNextInstruction to skip the label and
  11289. optional align marker. [Kit] }
  11290. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  11291. { remove Jcc }
  11292. RemoveInstruction(hp1);
  11293. { Now we can safely decrement it }
  11294. tasmlabel(symbol).decrefs;
  11295. { Remove label xxx (it will have a ref of zero due to the initial check) }
  11296. { Make sure the aligns get stripped too }
  11297. hp1 := tai(hp_lblxxx.Previous);
  11298. while Assigned(hp1) and (hp1.typ = ait_align) do
  11299. begin
  11300. hp_lblxxx := hp1;
  11301. hp1 := tai(hp_lblxxx.Previous);
  11302. end;
  11303. StripLabelFast(hp_lblxxx);
  11304. { remove jmp }
  11305. symbol := taicpu(hp_jump).oper[0]^.ref^.symbol;
  11306. RemoveInstruction(hp_jump);
  11307. { As before, now we can safely decrement it }
  11308. TAsmLabel(symbol).decrefs;
  11309. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  11310. if TAsmLabel(symbol).getrefs = 0 then
  11311. begin
  11312. { Make sure the aligns get stripped too }
  11313. hp1 := tai(hp_lblyyy.Previous);
  11314. while Assigned(hp1) and (hp1.typ = ait_align) do
  11315. begin
  11316. hp_lblyyy := hp1;
  11317. hp1 := tai(hp_lblyyy.Previous);
  11318. end;
  11319. StripLabelFast(hp_lblyyy);
  11320. end;
  11321. if Assigned(p) then
  11322. result := True;
  11323. exit;
  11324. end;
  11325. end;
  11326. end;
  11327. {$endif i8086}
  11328. end;
  11329. end;
  11330. end;
  11331. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  11332. var
  11333. hp1,hp2,hp3: tai;
  11334. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  11335. NewSize: TOpSize;
  11336. NewRegSize: TSubRegister;
  11337. Limit: TCgInt;
  11338. SwapOper: POper;
  11339. begin
  11340. result:=false;
  11341. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  11342. GetNextInstruction(p,hp1) and
  11343. (hp1.typ = ait_instruction);
  11344. if reg_and_hp1_is_instr and
  11345. (
  11346. (taicpu(hp1).opcode <> A_LEA) or
  11347. { If the LEA instruction can be converted into an arithmetic instruction,
  11348. it may be possible to then fold it. }
  11349. (
  11350. { If the flags register is in use, don't change the instruction
  11351. to an ADD otherwise this will scramble the flags. [Kit] }
  11352. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11353. ConvertLEA(taicpu(hp1))
  11354. )
  11355. ) and
  11356. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  11357. GetNextInstruction(hp1,hp2) and
  11358. MatchInstruction(hp2,A_MOV,[]) and
  11359. (taicpu(hp2).oper[0]^.typ = top_reg) and
  11360. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  11361. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  11362. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  11363. {$ifdef i386}
  11364. { not all registers have byte size sub registers on i386 }
  11365. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  11366. {$endif i386}
  11367. (((taicpu(hp1).ops=2) and
  11368. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  11369. ((taicpu(hp1).ops=1) and
  11370. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  11371. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  11372. begin
  11373. { change movsX/movzX reg/ref, reg2
  11374. add/sub/or/... reg3/$const, reg2
  11375. mov reg2 reg/ref
  11376. to add/sub/or/... reg3/$const, reg/ref }
  11377. { by example:
  11378. movswl %si,%eax movswl %si,%eax p
  11379. decl %eax addl %edx,%eax hp1
  11380. movw %ax,%si movw %ax,%si hp2
  11381. ->
  11382. movswl %si,%eax movswl %si,%eax p
  11383. decw %eax addw %edx,%eax hp1
  11384. movw %ax,%si movw %ax,%si hp2
  11385. }
  11386. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  11387. {
  11388. ->
  11389. movswl %si,%eax movswl %si,%eax p
  11390. decw %si addw %dx,%si hp1
  11391. movw %ax,%si movw %ax,%si hp2
  11392. }
  11393. case taicpu(hp1).ops of
  11394. 1:
  11395. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  11396. 2:
  11397. begin
  11398. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  11399. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  11400. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  11401. end;
  11402. else
  11403. internalerror(2008042702);
  11404. end;
  11405. {
  11406. ->
  11407. decw %si addw %dx,%si p
  11408. }
  11409. DebugMsg(SPeepholeOptimization + 'var3',p);
  11410. RemoveCurrentP(p, hp1);
  11411. RemoveInstruction(hp2);
  11412. Result := True;
  11413. Exit;
  11414. end;
  11415. if reg_and_hp1_is_instr and
  11416. (taicpu(hp1).opcode = A_MOV) and
  11417. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11418. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  11419. {$ifdef x86_64}
  11420. { check for implicit extension to 64 bit }
  11421. or
  11422. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11423. (taicpu(hp1).opsize=S_Q) and
  11424. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  11425. )
  11426. {$endif x86_64}
  11427. )
  11428. then
  11429. begin
  11430. { change
  11431. movx %reg1,%reg2
  11432. mov %reg2,%reg3
  11433. dealloc %reg2
  11434. into
  11435. movx %reg,%reg3
  11436. }
  11437. TransferUsedRegs(TmpUsedRegs);
  11438. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11439. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  11440. begin
  11441. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  11442. {$ifdef x86_64}
  11443. if (taicpu(p).opsize in [S_BL,S_WL]) and
  11444. (taicpu(hp1).opsize=S_Q) then
  11445. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  11446. else
  11447. {$endif x86_64}
  11448. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  11449. RemoveInstruction(hp1);
  11450. Result := True;
  11451. Exit;
  11452. end;
  11453. end;
  11454. if reg_and_hp1_is_instr and
  11455. ((taicpu(hp1).opcode=A_MOV) or
  11456. (taicpu(hp1).opcode=A_ADD) or
  11457. (taicpu(hp1).opcode=A_SUB) or
  11458. (taicpu(hp1).opcode=A_CMP) or
  11459. (taicpu(hp1).opcode=A_OR) or
  11460. (taicpu(hp1).opcode=A_XOR) or
  11461. (taicpu(hp1).opcode=A_AND)
  11462. ) and
  11463. (taicpu(hp1).oper[1]^.typ = top_reg) then
  11464. begin
  11465. AndTest := (taicpu(hp1).opcode=A_AND) and
  11466. GetNextInstruction(hp1, hp2) and
  11467. (hp2.typ = ait_instruction) and
  11468. (
  11469. (
  11470. (taicpu(hp2).opcode=A_TEST) and
  11471. (
  11472. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  11473. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  11474. (
  11475. { If the AND and TEST instructions share a constant, this is also valid }
  11476. (taicpu(hp1).oper[0]^.typ = top_const) and
  11477. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  11478. )
  11479. ) and
  11480. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11481. ) or
  11482. (
  11483. (taicpu(hp2).opcode=A_CMP) and
  11484. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  11485. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  11486. )
  11487. );
  11488. { change
  11489. movx (oper),%reg2
  11490. and $x,%reg2
  11491. test %reg2,%reg2
  11492. dealloc %reg2
  11493. into
  11494. op %reg1,%reg3
  11495. if the second op accesses only the bits stored in reg1
  11496. }
  11497. if ((taicpu(p).oper[0]^.typ=top_reg) or
  11498. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  11499. (taicpu(hp1).oper[0]^.typ = top_const) and
  11500. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  11501. AndTest then
  11502. begin
  11503. { Check if the AND constant is in range }
  11504. case taicpu(p).opsize of
  11505. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11506. begin
  11507. NewSize := S_B;
  11508. Limit := $FF;
  11509. end;
  11510. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11511. begin
  11512. NewSize := S_W;
  11513. Limit := $FFFF;
  11514. end;
  11515. {$ifdef x86_64}
  11516. S_LQ:
  11517. begin
  11518. NewSize := S_L;
  11519. Limit := $FFFFFFFF;
  11520. end;
  11521. {$endif x86_64}
  11522. else
  11523. InternalError(2021120303);
  11524. end;
  11525. if (
  11526. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  11527. { Check for negative operands }
  11528. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  11529. ) and
  11530. GetNextInstruction(hp2,hp3) and
  11531. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  11532. (taicpu(hp3).condition in [C_E,C_NE]) then
  11533. begin
  11534. TransferUsedRegs(TmpUsedRegs);
  11535. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11536. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11537. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  11538. begin
  11539. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  11540. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11541. taicpu(hp1).opcode := A_TEST;
  11542. taicpu(hp1).opsize := NewSize;
  11543. RemoveInstruction(hp2);
  11544. RemoveCurrentP(p, hp1);
  11545. Result:=true;
  11546. exit;
  11547. end;
  11548. end;
  11549. end;
  11550. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11551. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  11552. (taicpu(hp1).opsize=S_B)) or
  11553. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  11554. (taicpu(hp1).opsize=S_W))
  11555. {$ifdef x86_64}
  11556. or ((taicpu(p).opsize=S_LQ) and
  11557. (taicpu(hp1).opsize=S_L))
  11558. {$endif x86_64}
  11559. ) and
  11560. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  11561. begin
  11562. { change
  11563. movx %reg1,%reg2
  11564. op %reg2,%reg3
  11565. dealloc %reg2
  11566. into
  11567. op %reg1,%reg3
  11568. if the second op accesses only the bits stored in reg1
  11569. }
  11570. TransferUsedRegs(TmpUsedRegs);
  11571. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11572. if AndTest then
  11573. begin
  11574. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11575. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11576. end
  11577. else
  11578. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11579. if not RegUsed then
  11580. begin
  11581. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  11582. if taicpu(p).oper[0]^.typ=top_reg then
  11583. begin
  11584. case taicpu(hp1).opsize of
  11585. S_B:
  11586. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  11587. S_W:
  11588. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  11589. S_L:
  11590. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  11591. else
  11592. Internalerror(2020102301);
  11593. end;
  11594. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  11595. end
  11596. else
  11597. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  11598. RemoveCurrentP(p);
  11599. if AndTest then
  11600. RemoveInstruction(hp2);
  11601. result:=true;
  11602. exit;
  11603. end;
  11604. end
  11605. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11606. (
  11607. { Bitwise operations only }
  11608. (taicpu(hp1).opcode=A_AND) or
  11609. (taicpu(hp1).opcode=A_TEST) or
  11610. (
  11611. (taicpu(hp1).oper[0]^.typ = top_const) and
  11612. (
  11613. (taicpu(hp1).opcode=A_OR) or
  11614. (taicpu(hp1).opcode=A_XOR)
  11615. )
  11616. )
  11617. ) and
  11618. (
  11619. (taicpu(hp1).oper[0]^.typ = top_const) or
  11620. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  11621. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  11622. ) then
  11623. begin
  11624. { change
  11625. movx %reg2,%reg2
  11626. op const,%reg2
  11627. into
  11628. op const,%reg2 (smaller version)
  11629. movx %reg2,%reg2
  11630. also change
  11631. movx %reg1,%reg2
  11632. and/test (oper),%reg2
  11633. dealloc %reg2
  11634. into
  11635. and/test (oper),%reg1
  11636. }
  11637. case taicpu(p).opsize of
  11638. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11639. begin
  11640. NewSize := S_B;
  11641. NewRegSize := R_SUBL;
  11642. Limit := $FF;
  11643. end;
  11644. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11645. begin
  11646. NewSize := S_W;
  11647. NewRegSize := R_SUBW;
  11648. Limit := $FFFF;
  11649. end;
  11650. {$ifdef x86_64}
  11651. S_LQ:
  11652. begin
  11653. NewSize := S_L;
  11654. NewRegSize := R_SUBD;
  11655. Limit := $FFFFFFFF;
  11656. end;
  11657. {$endif x86_64}
  11658. else
  11659. Internalerror(2021120302);
  11660. end;
  11661. TransferUsedRegs(TmpUsedRegs);
  11662. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  11663. if AndTest then
  11664. begin
  11665. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  11666. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  11667. end
  11668. else
  11669. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  11670. if
  11671. (
  11672. (taicpu(p).opcode = A_MOVZX) and
  11673. (
  11674. (taicpu(hp1).opcode=A_AND) or
  11675. (taicpu(hp1).opcode=A_TEST)
  11676. ) and
  11677. not (
  11678. { If both are references, then the final instruction will have
  11679. both operands as references, which is not allowed }
  11680. (taicpu(p).oper[0]^.typ = top_ref) and
  11681. (taicpu(hp1).oper[0]^.typ = top_ref)
  11682. ) and
  11683. not RegUsed
  11684. ) or
  11685. (
  11686. (
  11687. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  11688. not RegUsed
  11689. ) and
  11690. (taicpu(p).oper[0]^.typ = top_reg) and
  11691. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11692. (taicpu(hp1).oper[0]^.typ = top_const) and
  11693. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  11694. ) then
  11695. begin
  11696. {$if defined(i386) or defined(i8086)}
  11697. { If the target size is 8-bit, make sure we can actually encode it }
  11698. 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
  11699. Exit;
  11700. {$endif i386 or i8086}
  11701. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  11702. taicpu(hp1).opsize := NewSize;
  11703. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  11704. if AndTest then
  11705. begin
  11706. RemoveInstruction(hp2);
  11707. if not RegUsed then
  11708. begin
  11709. taicpu(hp1).opcode := A_TEST;
  11710. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  11711. begin
  11712. { Make sure the reference is the second operand }
  11713. SwapOper := taicpu(hp1).oper[0];
  11714. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  11715. taicpu(hp1).oper[1] := SwapOper;
  11716. end;
  11717. end;
  11718. end;
  11719. case taicpu(hp1).oper[0]^.typ of
  11720. top_reg:
  11721. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  11722. top_const:
  11723. { For the AND/TEST case }
  11724. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  11725. else
  11726. ;
  11727. end;
  11728. if RegUsed then
  11729. begin
  11730. AsmL.Remove(p);
  11731. AsmL.InsertAfter(p, hp1);
  11732. p := hp1;
  11733. end
  11734. else
  11735. RemoveCurrentP(p, hp1);
  11736. result:=true;
  11737. exit;
  11738. end;
  11739. end;
  11740. end;
  11741. if reg_and_hp1_is_instr and
  11742. (taicpu(p).oper[0]^.typ = top_reg) and
  11743. (
  11744. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  11745. ) and
  11746. (taicpu(hp1).oper[0]^.typ = top_const) and
  11747. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11748. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11749. { Minimum shift value allowed is the bit difference between the sizes }
  11750. (taicpu(hp1).oper[0]^.val >=
  11751. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  11752. 8 * (
  11753. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  11754. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  11755. )
  11756. ) then
  11757. begin
  11758. { For:
  11759. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  11760. shl/sal ##, %reg1
  11761. Remove the movsx/movzx instruction if the shift overwrites the
  11762. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  11763. }
  11764. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  11765. RemoveCurrentP(p, hp1);
  11766. Result := True;
  11767. Exit;
  11768. end
  11769. else if reg_and_hp1_is_instr and
  11770. (taicpu(p).oper[0]^.typ = top_reg) and
  11771. (
  11772. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  11773. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  11774. ) and
  11775. (taicpu(hp1).oper[0]^.typ = top_const) and
  11776. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11777. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11778. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  11779. (taicpu(hp1).oper[0]^.val <
  11780. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  11781. 8 * (
  11782. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  11783. )
  11784. ) then
  11785. begin
  11786. { For:
  11787. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  11788. sar ##, %reg1 shr ##, %reg1
  11789. Move the shift to before the movx instruction if the shift value
  11790. is not too large.
  11791. }
  11792. asml.Remove(hp1);
  11793. asml.InsertBefore(hp1, p);
  11794. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  11795. case taicpu(p).opsize of
  11796. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  11797. taicpu(hp1).opsize := S_B;
  11798. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  11799. taicpu(hp1).opsize := S_W;
  11800. {$ifdef x86_64}
  11801. S_LQ:
  11802. taicpu(hp1).opsize := S_L;
  11803. {$endif}
  11804. else
  11805. InternalError(2020112401);
  11806. end;
  11807. if (taicpu(hp1).opcode = A_SHR) then
  11808. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  11809. else
  11810. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  11811. Result := True;
  11812. end;
  11813. if reg_and_hp1_is_instr and
  11814. (taicpu(p).oper[0]^.typ = top_reg) and
  11815. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  11816. (
  11817. (taicpu(hp1).opcode = taicpu(p).opcode)
  11818. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  11819. {$ifdef x86_64}
  11820. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  11821. {$endif x86_64}
  11822. ) then
  11823. begin
  11824. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  11825. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  11826. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  11827. begin
  11828. {
  11829. For example:
  11830. movzbw %al,%ax
  11831. movzwl %ax,%eax
  11832. Compress into:
  11833. movzbl %al,%eax
  11834. }
  11835. RegUsed := False;
  11836. case taicpu(p).opsize of
  11837. S_BW:
  11838. case taicpu(hp1).opsize of
  11839. S_WL:
  11840. begin
  11841. taicpu(p).opsize := S_BL;
  11842. RegUsed := True;
  11843. end;
  11844. {$ifdef x86_64}
  11845. S_WQ:
  11846. begin
  11847. if taicpu(p).opcode = A_MOVZX then
  11848. begin
  11849. taicpu(p).opsize := S_BL;
  11850. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11851. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11852. end
  11853. else
  11854. taicpu(p).opsize := S_BQ;
  11855. RegUsed := True;
  11856. end;
  11857. {$endif x86_64}
  11858. else
  11859. ;
  11860. end;
  11861. {$ifdef x86_64}
  11862. S_BL:
  11863. case taicpu(hp1).opsize of
  11864. S_LQ:
  11865. begin
  11866. if taicpu(p).opcode = A_MOVZX then
  11867. begin
  11868. taicpu(p).opsize := S_BL;
  11869. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11870. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11871. end
  11872. else
  11873. taicpu(p).opsize := S_BQ;
  11874. RegUsed := True;
  11875. end;
  11876. else
  11877. ;
  11878. end;
  11879. S_WL:
  11880. case taicpu(hp1).opsize of
  11881. S_LQ:
  11882. begin
  11883. if taicpu(p).opcode = A_MOVZX then
  11884. begin
  11885. taicpu(p).opsize := S_WL;
  11886. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11887. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11888. end
  11889. else
  11890. taicpu(p).opsize := S_WQ;
  11891. RegUsed := True;
  11892. end;
  11893. else
  11894. ;
  11895. end;
  11896. {$endif x86_64}
  11897. else
  11898. ;
  11899. end;
  11900. if RegUsed then
  11901. begin
  11902. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  11903. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  11904. RemoveInstruction(hp1);
  11905. Result := True;
  11906. Exit;
  11907. end;
  11908. end;
  11909. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  11910. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  11911. GetNextInstruction(hp1, hp2) and
  11912. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  11913. (
  11914. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  11915. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  11916. {$ifdef x86_64}
  11917. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  11918. {$endif x86_64}
  11919. ) and
  11920. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11921. (
  11922. (
  11923. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11924. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  11925. ) or
  11926. (
  11927. { Only allow the operands in reverse order for TEST instructions }
  11928. (taicpu(hp2).opcode = A_TEST) and
  11929. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11930. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  11931. )
  11932. ) then
  11933. begin
  11934. {
  11935. For example:
  11936. movzbl %al,%eax
  11937. movzbl (ref),%edx
  11938. andl %edx,%eax
  11939. (%edx deallocated)
  11940. Change to:
  11941. andb (ref),%al
  11942. movzbl %al,%eax
  11943. Rules are:
  11944. - First two instructions have the same opcode and opsize
  11945. - First instruction's operands are the same super-register
  11946. - Second instruction operates on a different register
  11947. - Third instruction is AND, OR, XOR or TEST
  11948. - Third instruction's operands are the destination registers of the first two instructions
  11949. - Third instruction writes to the destination register of the first instruction (except with TEST)
  11950. - Second instruction's destination register is deallocated afterwards
  11951. }
  11952. TransferUsedRegs(TmpUsedRegs);
  11953. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11954. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11955. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  11956. begin
  11957. case taicpu(p).opsize of
  11958. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11959. NewSize := S_B;
  11960. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11961. NewSize := S_W;
  11962. {$ifdef x86_64}
  11963. S_LQ:
  11964. NewSize := S_L;
  11965. {$endif x86_64}
  11966. else
  11967. InternalError(2021120301);
  11968. end;
  11969. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  11970. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  11971. taicpu(hp2).opsize := NewSize;
  11972. RemoveInstruction(hp1);
  11973. { With TEST, it's best to keep the MOVX instruction at the top }
  11974. if (taicpu(hp2).opcode <> A_TEST) then
  11975. begin
  11976. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  11977. asml.Remove(p);
  11978. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  11979. asml.InsertAfter(p, hp2);
  11980. p := hp2;
  11981. end
  11982. else
  11983. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  11984. Result := True;
  11985. Exit;
  11986. end;
  11987. end;
  11988. end;
  11989. if taicpu(p).opcode=A_MOVZX then
  11990. begin
  11991. { removes superfluous And's after movzx's }
  11992. if reg_and_hp1_is_instr and
  11993. (taicpu(hp1).opcode = A_AND) and
  11994. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11995. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  11996. {$ifdef x86_64}
  11997. { check for implicit extension to 64 bit }
  11998. or
  11999. ((taicpu(p).opsize in [S_BL,S_WL]) and
  12000. (taicpu(hp1).opsize=S_Q) and
  12001. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  12002. )
  12003. {$endif x86_64}
  12004. )
  12005. then
  12006. begin
  12007. case taicpu(p).opsize Of
  12008. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12009. if (taicpu(hp1).oper[0]^.val = $ff) then
  12010. begin
  12011. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  12012. RemoveInstruction(hp1);
  12013. Result:=true;
  12014. exit;
  12015. end;
  12016. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12017. if (taicpu(hp1).oper[0]^.val = $ffff) then
  12018. begin
  12019. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  12020. RemoveInstruction(hp1);
  12021. Result:=true;
  12022. exit;
  12023. end;
  12024. {$ifdef x86_64}
  12025. S_LQ:
  12026. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  12027. begin
  12028. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  12029. RemoveInstruction(hp1);
  12030. Result:=true;
  12031. exit;
  12032. end;
  12033. {$endif x86_64}
  12034. else
  12035. ;
  12036. end;
  12037. { we cannot get rid of the and, but can we get rid of the movz ?}
  12038. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  12039. begin
  12040. case taicpu(p).opsize Of
  12041. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12042. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  12043. begin
  12044. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  12045. RemoveCurrentP(p,hp1);
  12046. Result:=true;
  12047. exit;
  12048. end;
  12049. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12050. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  12051. begin
  12052. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  12053. RemoveCurrentP(p,hp1);
  12054. Result:=true;
  12055. exit;
  12056. end;
  12057. {$ifdef x86_64}
  12058. S_LQ:
  12059. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  12060. begin
  12061. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  12062. RemoveCurrentP(p,hp1);
  12063. Result:=true;
  12064. exit;
  12065. end;
  12066. {$endif x86_64}
  12067. else
  12068. ;
  12069. end;
  12070. end;
  12071. end;
  12072. { changes some movzx constructs to faster synonyms (all examples
  12073. are given with eax/ax, but are also valid for other registers)}
  12074. if MatchOpType(taicpu(p),top_reg,top_reg) then
  12075. begin
  12076. case taicpu(p).opsize of
  12077. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  12078. (the machine code is equivalent to movzbl %al,%eax), but the
  12079. code generator still generates that assembler instruction and
  12080. it is silently converted. This should probably be checked.
  12081. [Kit] }
  12082. S_BW:
  12083. begin
  12084. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  12085. (
  12086. not IsMOVZXAcceptable
  12087. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  12088. or (
  12089. (cs_opt_size in current_settings.optimizerswitches) and
  12090. (taicpu(p).oper[1]^.reg = NR_AX)
  12091. )
  12092. ) then
  12093. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  12094. begin
  12095. DebugMsg(SPeepholeOptimization + 'var7',p);
  12096. taicpu(p).opcode := A_AND;
  12097. taicpu(p).changeopsize(S_W);
  12098. taicpu(p).loadConst(0,$ff);
  12099. Result := True;
  12100. end
  12101. else if not IsMOVZXAcceptable and
  12102. GetNextInstruction(p, hp1) and
  12103. (tai(hp1).typ = ait_instruction) and
  12104. (taicpu(hp1).opcode = A_AND) and
  12105. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12106. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12107. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  12108. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  12109. begin
  12110. DebugMsg(SPeepholeOptimization + 'var8',p);
  12111. taicpu(p).opcode := A_MOV;
  12112. taicpu(p).changeopsize(S_W);
  12113. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  12114. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12115. Result := True;
  12116. end;
  12117. end;
  12118. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  12119. S_BL:
  12120. if not IsMOVZXAcceptable then
  12121. begin
  12122. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12123. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  12124. begin
  12125. DebugMsg(SPeepholeOptimization + 'var9',p);
  12126. taicpu(p).opcode := A_AND;
  12127. taicpu(p).changeopsize(S_L);
  12128. taicpu(p).loadConst(0,$ff);
  12129. Result := True;
  12130. end
  12131. else if GetNextInstruction(p, hp1) and
  12132. (tai(hp1).typ = ait_instruction) and
  12133. (taicpu(hp1).opcode = A_AND) and
  12134. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12135. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12136. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  12137. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  12138. begin
  12139. DebugMsg(SPeepholeOptimization + 'var10',p);
  12140. taicpu(p).opcode := A_MOV;
  12141. taicpu(p).changeopsize(S_L);
  12142. { do not use R_SUBWHOLE
  12143. as movl %rdx,%eax
  12144. is invalid in assembler PM }
  12145. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12146. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12147. Result := True;
  12148. end;
  12149. end;
  12150. {$endif i8086}
  12151. S_WL:
  12152. if not IsMOVZXAcceptable then
  12153. begin
  12154. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  12155. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  12156. begin
  12157. DebugMsg(SPeepholeOptimization + 'var11',p);
  12158. taicpu(p).opcode := A_AND;
  12159. taicpu(p).changeopsize(S_L);
  12160. taicpu(p).loadConst(0,$ffff);
  12161. Result := True;
  12162. end
  12163. else if GetNextInstruction(p, hp1) and
  12164. (tai(hp1).typ = ait_instruction) and
  12165. (taicpu(hp1).opcode = A_AND) and
  12166. (taicpu(hp1).oper[0]^.typ = top_const) and
  12167. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12168. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12169. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  12170. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  12171. begin
  12172. DebugMsg(SPeepholeOptimization + 'var12',p);
  12173. taicpu(p).opcode := A_MOV;
  12174. taicpu(p).changeopsize(S_L);
  12175. { do not use R_SUBWHOLE
  12176. as movl %rdx,%eax
  12177. is invalid in assembler PM }
  12178. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  12179. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12180. Result := True;
  12181. end;
  12182. end;
  12183. else
  12184. InternalError(2017050705);
  12185. end;
  12186. end
  12187. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  12188. begin
  12189. if GetNextInstruction(p, hp1) and
  12190. (tai(hp1).typ = ait_instruction) and
  12191. (taicpu(hp1).opcode = A_AND) and
  12192. MatchOpType(taicpu(hp1),top_const,top_reg) and
  12193. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12194. begin
  12195. //taicpu(p).opcode := A_MOV;
  12196. case taicpu(p).opsize Of
  12197. S_BL:
  12198. begin
  12199. DebugMsg(SPeepholeOptimization + 'var13',p);
  12200. taicpu(hp1).changeopsize(S_L);
  12201. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12202. end;
  12203. S_WL:
  12204. begin
  12205. DebugMsg(SPeepholeOptimization + 'var14',p);
  12206. taicpu(hp1).changeopsize(S_L);
  12207. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  12208. end;
  12209. S_BW:
  12210. begin
  12211. DebugMsg(SPeepholeOptimization + 'var15',p);
  12212. taicpu(hp1).changeopsize(S_W);
  12213. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  12214. end;
  12215. else
  12216. Internalerror(2017050704)
  12217. end;
  12218. Result := True;
  12219. end;
  12220. end;
  12221. end;
  12222. end;
  12223. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  12224. var
  12225. hp1, hp2 : tai;
  12226. MaskLength : Cardinal;
  12227. MaskedBits : TCgInt;
  12228. ActiveReg : TRegister;
  12229. begin
  12230. Result:=false;
  12231. { There are no optimisations for reference targets }
  12232. if (taicpu(p).oper[1]^.typ <> top_reg) then
  12233. Exit;
  12234. while GetNextInstruction(p, hp1) and
  12235. (hp1.typ = ait_instruction) do
  12236. begin
  12237. if (taicpu(p).oper[0]^.typ = top_const) then
  12238. begin
  12239. case taicpu(hp1).opcode of
  12240. A_AND:
  12241. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12242. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12243. { the second register must contain the first one, so compare their subreg types }
  12244. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  12245. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  12246. { change
  12247. and const1, reg
  12248. and const2, reg
  12249. to
  12250. and (const1 and const2), reg
  12251. }
  12252. begin
  12253. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  12254. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  12255. RemoveCurrentP(p, hp1);
  12256. Result:=true;
  12257. exit;
  12258. end;
  12259. A_CMP:
  12260. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  12261. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  12262. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  12263. { Just check that the condition on the next instruction is compatible }
  12264. GetNextInstruction(hp1, hp2) and
  12265. (hp2.typ = ait_instruction) and
  12266. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  12267. then
  12268. { change
  12269. and 2^n, reg
  12270. cmp 2^n, reg
  12271. j(c) / set(c) / cmov(c) (c is equal or not equal)
  12272. to
  12273. and 2^n, reg
  12274. test reg, reg
  12275. j(~c) / set(~c) / cmov(~c)
  12276. }
  12277. begin
  12278. { Keep TEST instruction in, rather than remove it, because
  12279. it may trigger other optimisations such as MovAndTest2Test }
  12280. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  12281. taicpu(hp1).opcode := A_TEST;
  12282. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  12283. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  12284. Result := True;
  12285. Exit;
  12286. end;
  12287. A_MOVZX:
  12288. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  12289. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  12290. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  12291. (
  12292. (
  12293. (taicpu(p).opsize=S_W) and
  12294. (taicpu(hp1).opsize=S_BW)
  12295. ) or
  12296. (
  12297. (taicpu(p).opsize=S_L) and
  12298. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  12299. )
  12300. {$ifdef x86_64}
  12301. or
  12302. (
  12303. (taicpu(p).opsize=S_Q) and
  12304. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  12305. )
  12306. {$endif x86_64}
  12307. ) then
  12308. begin
  12309. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12310. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  12311. ) or
  12312. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12313. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  12314. then
  12315. begin
  12316. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  12317. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  12318. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  12319. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  12320. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  12321. }
  12322. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  12323. RemoveInstruction(hp1);
  12324. { See if there are other optimisations possible }
  12325. Continue;
  12326. end;
  12327. end;
  12328. A_SHL:
  12329. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12330. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  12331. begin
  12332. {$ifopt R+}
  12333. {$define RANGE_WAS_ON}
  12334. {$R-}
  12335. {$endif}
  12336. { get length of potential and mask }
  12337. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  12338. { really a mask? }
  12339. {$ifdef RANGE_WAS_ON}
  12340. {$R+}
  12341. {$endif}
  12342. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  12343. { unmasked part shifted out? }
  12344. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  12345. begin
  12346. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  12347. RemoveCurrentP(p, hp1);
  12348. Result:=true;
  12349. exit;
  12350. end;
  12351. end;
  12352. A_SHR:
  12353. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  12354. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  12355. (taicpu(hp1).oper[0]^.val <= 63) then
  12356. begin
  12357. { Does SHR combined with the AND cover all the bits?
  12358. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  12359. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  12360. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  12361. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  12362. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  12363. begin
  12364. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  12365. RemoveCurrentP(p, hp1);
  12366. Result := True;
  12367. Exit;
  12368. end;
  12369. end;
  12370. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12371. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  12372. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12373. begin
  12374. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12375. (
  12376. (
  12377. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  12378. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  12379. ) or (
  12380. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  12381. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  12382. {$ifdef x86_64}
  12383. ) or (
  12384. (taicpu(hp1).opsize = S_LQ) and
  12385. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  12386. {$endif x86_64}
  12387. )
  12388. ) then
  12389. begin
  12390. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  12391. begin
  12392. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  12393. RemoveInstruction(hp1);
  12394. { See if there are other optimisations possible }
  12395. Continue;
  12396. end;
  12397. { The super-registers are the same though.
  12398. Note that this change by itself doesn't improve
  12399. code speed, but it opens up other optimisations. }
  12400. {$ifdef x86_64}
  12401. { Convert 64-bit register to 32-bit }
  12402. case taicpu(hp1).opsize of
  12403. S_BQ:
  12404. begin
  12405. taicpu(hp1).opsize := S_BL;
  12406. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12407. end;
  12408. S_WQ:
  12409. begin
  12410. taicpu(hp1).opsize := S_WL;
  12411. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  12412. end
  12413. else
  12414. ;
  12415. end;
  12416. {$endif x86_64}
  12417. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  12418. taicpu(hp1).opcode := A_MOVZX;
  12419. { See if there are other optimisations possible }
  12420. Continue;
  12421. end;
  12422. end;
  12423. else
  12424. ;
  12425. end;
  12426. end
  12427. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  12428. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  12429. begin
  12430. {$ifdef x86_64}
  12431. if (taicpu(p).opsize = S_Q) then
  12432. begin
  12433. { Never necessary }
  12434. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  12435. RemoveCurrentP(p, hp1);
  12436. Result := True;
  12437. Exit;
  12438. end;
  12439. {$endif x86_64}
  12440. { Forward check to determine necessity of and %reg,%reg }
  12441. TransferUsedRegs(TmpUsedRegs);
  12442. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12443. { Saves on a bunch of dereferences }
  12444. ActiveReg := taicpu(p).oper[1]^.reg;
  12445. case taicpu(hp1).opcode of
  12446. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  12447. if (
  12448. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12449. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12450. ) and
  12451. (
  12452. (taicpu(hp1).opcode <> A_MOV) or
  12453. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  12454. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  12455. ) and
  12456. not (
  12457. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  12458. (taicpu(hp1).opcode = A_MOV) and
  12459. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  12460. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  12461. ) and
  12462. (
  12463. (
  12464. (taicpu(hp1).oper[0]^.typ = top_reg) and
  12465. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  12466. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  12467. ) or
  12468. (
  12469. {$ifdef x86_64}
  12470. (
  12471. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  12472. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  12473. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  12474. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  12475. ) and
  12476. {$endif x86_64}
  12477. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  12478. )
  12479. ) then
  12480. begin
  12481. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  12482. RemoveCurrentP(p, hp1);
  12483. Result := True;
  12484. Exit;
  12485. end;
  12486. A_ADD,
  12487. A_AND,
  12488. A_BSF,
  12489. A_BSR,
  12490. A_BTC,
  12491. A_BTR,
  12492. A_BTS,
  12493. A_OR,
  12494. A_SUB,
  12495. A_XOR:
  12496. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  12497. if (
  12498. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12499. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12500. ) and
  12501. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  12502. begin
  12503. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  12504. RemoveCurrentP(p, hp1);
  12505. Result := True;
  12506. Exit;
  12507. end;
  12508. A_CMP,
  12509. A_TEST:
  12510. if (
  12511. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  12512. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  12513. ) and
  12514. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  12515. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  12516. begin
  12517. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  12518. RemoveCurrentP(p, hp1);
  12519. Result := True;
  12520. Exit;
  12521. end;
  12522. A_BSWAP,
  12523. A_NEG,
  12524. A_NOT:
  12525. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  12526. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  12527. begin
  12528. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  12529. RemoveCurrentP(p, hp1);
  12530. Result := True;
  12531. Exit;
  12532. end;
  12533. else
  12534. ;
  12535. end;
  12536. end;
  12537. if (taicpu(hp1).is_jmp) and
  12538. (taicpu(hp1).opcode<>A_JMP) and
  12539. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  12540. begin
  12541. { change
  12542. and x, reg
  12543. jxx
  12544. to
  12545. test x, reg
  12546. jxx
  12547. if reg is deallocated before the
  12548. jump, but only if it's a conditional jump (PFV)
  12549. }
  12550. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  12551. taicpu(p).opcode := A_TEST;
  12552. Exit;
  12553. end;
  12554. Break;
  12555. end;
  12556. { Lone AND tests }
  12557. if (taicpu(p).oper[0]^.typ = top_const) then
  12558. begin
  12559. {
  12560. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  12561. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  12562. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  12563. }
  12564. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  12565. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  12566. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  12567. begin
  12568. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  12569. if taicpu(p).opsize = S_L then
  12570. begin
  12571. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  12572. Result := True;
  12573. end;
  12574. end;
  12575. end;
  12576. { Backward check to determine necessity of and %reg,%reg }
  12577. if (taicpu(p).oper[0]^.typ = top_reg) and
  12578. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  12579. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12580. GetLastInstruction(p, hp2) and
  12581. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  12582. { Check size of adjacent instruction to determine if the AND is
  12583. effectively a null operation }
  12584. (
  12585. (taicpu(p).opsize = taicpu(hp2).opsize) or
  12586. { Note: Don't include S_Q }
  12587. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  12588. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  12589. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  12590. ) then
  12591. begin
  12592. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  12593. { If GetNextInstruction returned False, hp1 will be nil }
  12594. RemoveCurrentP(p, hp1);
  12595. Result := True;
  12596. Exit;
  12597. end;
  12598. end;
  12599. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  12600. var
  12601. hp1, hp2: tai;
  12602. NewRef: TReference;
  12603. Distance: Cardinal;
  12604. TempTracking: TAllUsedRegs;
  12605. { This entire nested function is used in an if-statement below, but we
  12606. want to avoid all the used reg transfers and GetNextInstruction calls
  12607. until we really have to check }
  12608. function MemRegisterNotUsedLater: Boolean; inline;
  12609. var
  12610. hp2: tai;
  12611. begin
  12612. TransferUsedRegs(TmpUsedRegs);
  12613. hp2 := p;
  12614. repeat
  12615. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12616. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12617. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  12618. end;
  12619. begin
  12620. Result := False;
  12621. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12622. (taicpu(p).oper[1]^.typ = top_reg) then
  12623. begin
  12624. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12625. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12626. (hp1.typ <> ait_instruction) or
  12627. not
  12628. (
  12629. (cs_opt_level3 in current_settings.optimizerswitches) or
  12630. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12631. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12632. ) then
  12633. Exit;
  12634. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12635. addq $x, %rax
  12636. movq %rax, %rdx
  12637. sarq $63, %rdx
  12638. (%rax still in use)
  12639. ...letting OptPass2ADD run its course (and without -Os) will produce:
  12640. leaq $x(%rax),%rdx
  12641. addq $x, %rax
  12642. sarq $63, %rdx
  12643. ...which is okay since it breaks the dependency chain between
  12644. addq and movq, but if OptPass2MOV is called first:
  12645. addq $x, %rax
  12646. cqto
  12647. ...which is better in all ways, taking only 2 cycles to execute
  12648. and much smaller in code size.
  12649. }
  12650. { The extra register tracking is quite strenuous }
  12651. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12652. MatchInstruction(hp1, A_MOV, []) then
  12653. begin
  12654. { Update the register tracking to the MOV instruction }
  12655. CopyUsedRegs(TempTracking);
  12656. hp2 := p;
  12657. repeat
  12658. UpdateUsedRegs(tai(hp2.Next));
  12659. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12660. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12661. OptPass2ADD get called again }
  12662. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12663. begin
  12664. { Reset the tracking to the current instruction }
  12665. RestoreUsedRegs(TempTracking);
  12666. ReleaseUsedRegs(TempTracking);
  12667. Result := True;
  12668. Exit;
  12669. end;
  12670. { Reset the tracking to the current instruction }
  12671. RestoreUsedRegs(TempTracking);
  12672. ReleaseUsedRegs(TempTracking);
  12673. { If OptPass2MOV returned True, we don't need to set Result to
  12674. True if hp1 didn't change because the ADD instruction didn't
  12675. get modified and we'll be evaluating hp1 again when the
  12676. peephole optimizer reaches it }
  12677. end;
  12678. { Change:
  12679. add %reg2,%reg1
  12680. (%reg2 not modified in between)
  12681. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  12682. To:
  12683. mov/s/z #(%reg1,%reg2),%reg1
  12684. }
  12685. if (taicpu(p).oper[0]^.typ = top_reg) and
  12686. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  12687. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  12688. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  12689. (
  12690. (
  12691. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  12692. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  12693. { r/esp cannot be an index }
  12694. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  12695. ) or (
  12696. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  12697. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  12698. )
  12699. ) and (
  12700. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  12701. (
  12702. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  12703. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  12704. MemRegisterNotUsedLater
  12705. )
  12706. ) then
  12707. begin
  12708. if (
  12709. { Instructions are guaranteed to be adjacent on -O2 and under }
  12710. (cs_opt_level3 in current_settings.optimizerswitches) and
  12711. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  12712. ) then
  12713. begin
  12714. { If the other register is used in between, move the MOV
  12715. instruction to right after the ADD instruction so a
  12716. saving can still be made }
  12717. Asml.Remove(hp1);
  12718. Asml.InsertAfter(hp1, p);
  12719. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  12720. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  12721. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  12722. RemoveCurrentp(p, hp1);
  12723. end
  12724. else
  12725. begin
  12726. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  12727. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  12728. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  12729. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  12730. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12731. { hp1 may not be the immediate next instruction under -O3 }
  12732. RemoveCurrentp(p)
  12733. else
  12734. RemoveCurrentp(p, hp1);
  12735. end;
  12736. Result := True;
  12737. Exit;
  12738. end;
  12739. { Change:
  12740. addl/q $x,%reg1
  12741. movl/q %reg1,%reg2
  12742. To:
  12743. leal/q $x(%reg1),%reg2
  12744. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  12745. Breaks the dependency chain.
  12746. }
  12747. if (taicpu(p).oper[0]^.typ = top_const) and
  12748. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  12749. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12750. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  12751. (
  12752. { Instructions are guaranteed to be adjacent on -O2 and under }
  12753. not (cs_opt_level3 in current_settings.optimizerswitches) or
  12754. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  12755. ) then
  12756. begin
  12757. TransferUsedRegs(TmpUsedRegs);
  12758. hp2 := p;
  12759. repeat
  12760. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12761. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12762. if (
  12763. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  12764. not (cs_opt_size in current_settings.optimizerswitches) or
  12765. (
  12766. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  12767. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  12768. )
  12769. ) then
  12770. begin
  12771. { Change the MOV instruction to a LEA instruction, and update the
  12772. first operand }
  12773. reference_reset(NewRef, 1, []);
  12774. NewRef.base := taicpu(p).oper[1]^.reg;
  12775. NewRef.scalefactor := 1;
  12776. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  12777. taicpu(hp1).opcode := A_LEA;
  12778. taicpu(hp1).loadref(0, NewRef);
  12779. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  12780. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12781. begin
  12782. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  12783. { Move what is now the LEA instruction to before the ADD instruction }
  12784. Asml.Remove(hp1);
  12785. Asml.InsertBefore(hp1, p);
  12786. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12787. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  12788. p := hp1;
  12789. end
  12790. else
  12791. begin
  12792. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  12793. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  12794. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12795. { hp1 may not be the immediate next instruction under -O3 }
  12796. RemoveCurrentp(p)
  12797. else
  12798. RemoveCurrentp(p, hp1);
  12799. end;
  12800. Result := True;
  12801. end;
  12802. end;
  12803. end;
  12804. end;
  12805. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  12806. var
  12807. SubReg: TSubRegister;
  12808. begin
  12809. Result:=false;
  12810. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  12811. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12812. with taicpu(p).oper[0]^.ref^ do
  12813. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  12814. begin
  12815. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  12816. begin
  12817. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  12818. taicpu(p).opcode := A_ADD;
  12819. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  12820. Result := True;
  12821. end
  12822. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  12823. begin
  12824. if (base <> NR_NO) then
  12825. begin
  12826. if (scalefactor <= 1) then
  12827. begin
  12828. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  12829. taicpu(p).opcode := A_ADD;
  12830. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  12831. Result := True;
  12832. end;
  12833. end
  12834. else
  12835. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  12836. if (scalefactor in [2, 4, 8]) then
  12837. begin
  12838. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  12839. taicpu(p).loadconst(0, BsrByte(scalefactor));
  12840. taicpu(p).opcode := A_SHL;
  12841. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  12842. Result := True;
  12843. end;
  12844. end;
  12845. end;
  12846. end;
  12847. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  12848. var
  12849. hp1, hp2: tai;
  12850. NewRef: TReference;
  12851. Distance: Cardinal;
  12852. TempTracking: TAllUsedRegs;
  12853. begin
  12854. Result := False;
  12855. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  12856. MatchOpType(taicpu(p),top_const,top_reg) then
  12857. begin
  12858. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  12859. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  12860. (hp1.typ <> ait_instruction) or
  12861. not
  12862. (
  12863. (cs_opt_level3 in current_settings.optimizerswitches) or
  12864. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  12865. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  12866. ) then
  12867. Exit;
  12868. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  12869. subq $x, %rax
  12870. movq %rax, %rdx
  12871. sarq $63, %rdx
  12872. (%rax still in use)
  12873. ...letting OptPass2SUB run its course (and without -Os) will produce:
  12874. leaq $-x(%rax),%rdx
  12875. movq $x, %rax
  12876. sarq $63, %rdx
  12877. ...which is okay since it breaks the dependency chain between
  12878. subq and movq, but if OptPass2MOV is called first:
  12879. subq $x, %rax
  12880. cqto
  12881. ...which is better in all ways, taking only 2 cycles to execute
  12882. and much smaller in code size.
  12883. }
  12884. { The extra register tracking is quite strenuous }
  12885. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12886. MatchInstruction(hp1, A_MOV, []) then
  12887. begin
  12888. { Update the register tracking to the MOV instruction }
  12889. CopyUsedRegs(TempTracking);
  12890. hp2 := p;
  12891. repeat
  12892. UpdateUsedRegs(tai(hp2.Next));
  12893. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12894. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12895. OptPass2SUB get called again }
  12896. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12897. begin
  12898. { Reset the tracking to the current instruction }
  12899. RestoreUsedRegs(TempTracking);
  12900. ReleaseUsedRegs(TempTracking);
  12901. Result := True;
  12902. Exit;
  12903. end;
  12904. { Reset the tracking to the current instruction }
  12905. RestoreUsedRegs(TempTracking);
  12906. ReleaseUsedRegs(TempTracking);
  12907. { If OptPass2MOV returned True, we don't need to set Result to
  12908. True if hp1 didn't change because the SUB instruction didn't
  12909. get modified and we'll be evaluating hp1 again when the
  12910. peephole optimizer reaches it }
  12911. end;
  12912. { Change:
  12913. subl/q $x,%reg1
  12914. movl/q %reg1,%reg2
  12915. To:
  12916. leal/q $-x(%reg1),%reg2
  12917. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  12918. Breaks the dependency chain and potentially permits the removal of
  12919. a CMP instruction if one follows.
  12920. }
  12921. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  12922. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12923. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  12924. (
  12925. { Instructions are guaranteed to be adjacent on -O2 and under }
  12926. not (cs_opt_level3 in current_settings.optimizerswitches) or
  12927. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  12928. ) then
  12929. begin
  12930. TransferUsedRegs(TmpUsedRegs);
  12931. hp2 := p;
  12932. repeat
  12933. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12934. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12935. if (
  12936. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  12937. not (cs_opt_size in current_settings.optimizerswitches) or
  12938. (
  12939. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  12940. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  12941. )
  12942. ) then
  12943. begin
  12944. { Change the MOV instruction to a LEA instruction, and update the
  12945. first operand }
  12946. reference_reset(NewRef, 1, []);
  12947. NewRef.base := taicpu(p).oper[1]^.reg;
  12948. NewRef.scalefactor := 1;
  12949. NewRef.offset := -taicpu(p).oper[0]^.val;
  12950. taicpu(hp1).opcode := A_LEA;
  12951. taicpu(hp1).loadref(0, NewRef);
  12952. TransferUsedRegs(TmpUsedRegs);
  12953. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12954. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  12955. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12956. begin
  12957. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  12958. { Move what is now the LEA instruction to before the SUB instruction }
  12959. Asml.Remove(hp1);
  12960. Asml.InsertBefore(hp1, p);
  12961. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12962. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  12963. p := hp1;
  12964. end
  12965. else
  12966. begin
  12967. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  12968. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  12969. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12970. { hp1 may not be the immediate next instruction under -O3 }
  12971. RemoveCurrentp(p)
  12972. else
  12973. RemoveCurrentp(p, hp1);
  12974. end;
  12975. Result := True;
  12976. end;
  12977. end;
  12978. end;
  12979. end;
  12980. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  12981. begin
  12982. { we can skip all instructions not messing with the stack pointer }
  12983. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  12984. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  12985. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  12986. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  12987. ({(taicpu(hp1).ops=0) or }
  12988. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  12989. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  12990. ) and }
  12991. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  12992. )
  12993. ) do
  12994. GetNextInstruction(hp1,hp1);
  12995. Result:=assigned(hp1);
  12996. end;
  12997. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  12998. var
  12999. hp1, hp2, hp3, hp4, hp5: tai;
  13000. begin
  13001. Result:=false;
  13002. hp5:=nil;
  13003. { replace
  13004. leal(q) x(<stackpointer>),<stackpointer>
  13005. call procname
  13006. leal(q) -x(<stackpointer>),<stackpointer>
  13007. ret
  13008. by
  13009. jmp procname
  13010. but do it only on level 4 because it destroys stack back traces
  13011. }
  13012. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13013. MatchOpType(taicpu(p),top_ref,top_reg) and
  13014. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13015. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  13016. { the -8 or -24 are not required, but bail out early if possible,
  13017. higher values are unlikely }
  13018. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  13019. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  13020. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  13021. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  13022. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13023. GetNextInstruction(p, hp1) and
  13024. { Take a copy of hp1 }
  13025. SetAndTest(hp1, hp4) and
  13026. { trick to skip label }
  13027. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13028. SkipSimpleInstructions(hp1) and
  13029. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13030. GetNextInstruction(hp1, hp2) and
  13031. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  13032. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  13033. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  13034. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  13035. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  13036. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  13037. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  13038. { Segment register will be NR_NO }
  13039. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  13040. GetNextInstruction(hp2, hp3) and
  13041. { trick to skip label }
  13042. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13043. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13044. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13045. SetAndTest(hp3,hp5) and
  13046. GetNextInstruction(hp3,hp3) and
  13047. MatchInstruction(hp3,A_RET,[S_NO])
  13048. )
  13049. ) and
  13050. (taicpu(hp3).ops=0) then
  13051. begin
  13052. taicpu(hp1).opcode := A_JMP;
  13053. taicpu(hp1).is_jmp := true;
  13054. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  13055. RemoveCurrentP(p, hp4);
  13056. RemoveInstruction(hp2);
  13057. RemoveInstruction(hp3);
  13058. if Assigned(hp5) then
  13059. begin
  13060. AsmL.Remove(hp5);
  13061. ASmL.InsertBefore(hp5,hp1)
  13062. end;
  13063. Result:=true;
  13064. end;
  13065. end;
  13066. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  13067. {$ifdef x86_64}
  13068. var
  13069. hp1, hp2, hp3, hp4, hp5: tai;
  13070. {$endif x86_64}
  13071. begin
  13072. Result:=false;
  13073. {$ifdef x86_64}
  13074. hp5:=nil;
  13075. { replace
  13076. push %rax
  13077. call procname
  13078. pop %rcx
  13079. ret
  13080. by
  13081. jmp procname
  13082. but do it only on level 4 because it destroys stack back traces
  13083. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  13084. for all supported calling conventions
  13085. }
  13086. if (cs_opt_level4 in current_settings.optimizerswitches) and
  13087. MatchOpType(taicpu(p),top_reg) and
  13088. (taicpu(p).oper[0]^.reg=NR_RAX) and
  13089. GetNextInstruction(p, hp1) and
  13090. { Take a copy of hp1 }
  13091. SetAndTest(hp1, hp4) and
  13092. { trick to skip label }
  13093. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  13094. SkipSimpleInstructions(hp1) and
  13095. MatchInstruction(hp1,A_CALL,[S_NO]) and
  13096. GetNextInstruction(hp1, hp2) and
  13097. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  13098. MatchOpType(taicpu(hp2),top_reg) and
  13099. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  13100. GetNextInstruction(hp2, hp3) and
  13101. { trick to skip label }
  13102. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  13103. (MatchInstruction(hp3,A_RET,[S_NO]) or
  13104. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  13105. SetAndTest(hp3,hp5) and
  13106. GetNextInstruction(hp3,hp3) and
  13107. MatchInstruction(hp3,A_RET,[S_NO])
  13108. )
  13109. ) and
  13110. (taicpu(hp3).ops=0) then
  13111. begin
  13112. taicpu(hp1).opcode := A_JMP;
  13113. taicpu(hp1).is_jmp := true;
  13114. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  13115. RemoveCurrentP(p, hp4);
  13116. RemoveInstruction(hp2);
  13117. RemoveInstruction(hp3);
  13118. if Assigned(hp5) then
  13119. begin
  13120. AsmL.Remove(hp5);
  13121. ASmL.InsertBefore(hp5,hp1)
  13122. end;
  13123. Result:=true;
  13124. end;
  13125. {$endif x86_64}
  13126. end;
  13127. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  13128. var
  13129. Value, RegName: string;
  13130. begin
  13131. Result:=false;
  13132. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  13133. begin
  13134. case taicpu(p).oper[0]^.val of
  13135. 0:
  13136. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  13137. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13138. begin
  13139. { change "mov $0,%reg" into "xor %reg,%reg" }
  13140. taicpu(p).opcode := A_XOR;
  13141. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  13142. Result := True;
  13143. {$ifdef x86_64}
  13144. end
  13145. else if (taicpu(p).opsize = S_Q) then
  13146. begin
  13147. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13148. { The actual optimization }
  13149. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13150. taicpu(p).changeopsize(S_L);
  13151. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13152. Result := True;
  13153. end;
  13154. $1..$FFFFFFFF:
  13155. begin
  13156. { Code size reduction by J. Gareth "Kit" Moreton }
  13157. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  13158. case taicpu(p).opsize of
  13159. S_Q:
  13160. begin
  13161. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  13162. Value := debug_tostr(taicpu(p).oper[0]^.val);
  13163. { The actual optimization }
  13164. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13165. taicpu(p).changeopsize(S_L);
  13166. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  13167. Result := True;
  13168. end;
  13169. else
  13170. { Do nothing };
  13171. end;
  13172. {$endif x86_64}
  13173. end;
  13174. -1:
  13175. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  13176. if (cs_opt_size in current_settings.optimizerswitches) and
  13177. (taicpu(p).opsize <> S_B) and
  13178. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  13179. begin
  13180. { change "mov $-1,%reg" into "or $-1,%reg" }
  13181. { NOTES:
  13182. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  13183. - This operation creates a false dependency on the register, so only do it when optimising for size
  13184. - 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
  13185. }
  13186. taicpu(p).opcode := A_OR;
  13187. DebugMsg(SPeepholeOptimization + 'Mov-12Or-1',p);
  13188. Result := True;
  13189. end;
  13190. else
  13191. { Do nothing };
  13192. end;
  13193. end;
  13194. end;
  13195. { Returns true if the given logic instruction can be converted into a BTx instruction (BT not included) }
  13196. class function TX86AsmOptimizer.IsBTXAcceptable(p : tai) : boolean;
  13197. begin
  13198. Result := False;
  13199. if not (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) then
  13200. Exit;
  13201. { For sizes less than S_L, the byte size is equal or larger with BTx,
  13202. so don't bother optimising }
  13203. if not MatchInstruction(p, A_AND, A_OR, A_XOR, [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  13204. Exit;
  13205. if (taicpu(p).oper[0]^.typ <> top_const) or
  13206. { If the value can fit into an 8-bit signed integer, a smaller
  13207. instruction can be encoded with AND/OR/XOR, so don't optimise if it
  13208. falls within this range }
  13209. (
  13210. (taicpu(p).oper[0]^.val > -128) and
  13211. (taicpu(p).oper[0]^.val <= 127)
  13212. ) then
  13213. Exit;
  13214. { If we're optimising for size, this is acceptable }
  13215. if (cs_opt_size in current_settings.optimizerswitches) then
  13216. Exit(True);
  13217. if (taicpu(p).oper[1]^.typ = top_reg) and
  13218. (CPUX86_HINT_FAST_BTX_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13219. Exit(True);
  13220. if (taicpu(p).oper[1]^.typ <> top_reg) and
  13221. (CPUX86_HINT_FAST_BTX_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype]) then
  13222. Exit(True);
  13223. end;
  13224. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  13225. var
  13226. hp1: tai;
  13227. Value: TCGInt;
  13228. begin
  13229. Result := False;
  13230. if MatchOpType(taicpu(p), top_const, top_reg) then
  13231. begin
  13232. { Detect:
  13233. andw x, %ax (0 <= x < $8000)
  13234. ...
  13235. movzwl %ax,%eax
  13236. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13237. }
  13238. if (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  13239. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  13240. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  13241. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  13242. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  13243. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  13244. begin
  13245. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  13246. taicpu(hp1).opcode := A_CWDE;
  13247. taicpu(hp1).clearop(0);
  13248. taicpu(hp1).clearop(1);
  13249. taicpu(hp1).ops := 0;
  13250. { A change was made, but not with p, so move forward 1 }
  13251. p := tai(p.Next);
  13252. Result := True;
  13253. Exit; { and -> btr won't happen because an opsize of S_W won't be optimised anyway }
  13254. end;
  13255. end;
  13256. { If "not x" is a power of 2 (popcnt = 1), change:
  13257. and $x, %reg/ref
  13258. To:
  13259. btr lb(x), %reg/ref
  13260. }
  13261. if IsBTXAcceptable(p) and
  13262. (
  13263. { Make sure a TEST doesn't follow that plays with the register }
  13264. not GetNextInstruction(p, hp1) or
  13265. not MatchInstruction(hp1, A_TEST, A_CMP, [taicpu(p).opsize]) or
  13266. not MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg)
  13267. ) then
  13268. begin
  13269. {$push}{$R-}{$Q-}
  13270. { Value is a sign-extended 32-bit integer - just correct it
  13271. if it's represented as an unsigned value. Also, IsBTXAcceptable
  13272. checks to see if this operand is an immediate. }
  13273. Value := not taicpu(p).oper[0]^.val;
  13274. {$pop}
  13275. {$ifdef x86_64}
  13276. if taicpu(p).opsize = S_L then
  13277. {$endif x86_64}
  13278. Value := Value and $FFFFFFFF;
  13279. if (PopCnt(QWord(Value)) = 1) then
  13280. begin
  13281. DebugMsg(SPeepholeOptimization + 'Changed AND (not $' + debug_hexstr(taicpu(p).oper[0]^.val) + ') to BTR $' + debug_tostr(BsrQWord(Value)) + ' to shrink instruction size (And2Btr)', p);
  13282. taicpu(p).opcode := A_BTR;
  13283. taicpu(p).oper[0]^.val := BsrQWord(Value); { Essentially the base 2 logarithm }
  13284. Result := True;
  13285. Exit;
  13286. end;
  13287. end;
  13288. end;
  13289. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  13290. begin
  13291. Result := False;
  13292. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  13293. Exit;
  13294. { Convert:
  13295. movswl %ax,%eax -> cwtl
  13296. movslq %eax,%rax -> cdqe
  13297. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  13298. refer to the same opcode and depends only on the assembler's
  13299. current operand-size attribute. [Kit]
  13300. }
  13301. with taicpu(p) do
  13302. case opsize of
  13303. S_WL:
  13304. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  13305. begin
  13306. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  13307. opcode := A_CWDE;
  13308. clearop(0);
  13309. clearop(1);
  13310. ops := 0;
  13311. Result := True;
  13312. end;
  13313. {$ifdef x86_64}
  13314. S_LQ:
  13315. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  13316. begin
  13317. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  13318. opcode := A_CDQE;
  13319. clearop(0);
  13320. clearop(1);
  13321. ops := 0;
  13322. Result := True;
  13323. end;
  13324. {$endif x86_64}
  13325. else
  13326. ;
  13327. end;
  13328. end;
  13329. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  13330. var
  13331. hp1, hp2: tai;
  13332. IdentityMask, Shift: TCGInt;
  13333. LimitSize: Topsize;
  13334. DoNotMerge: Boolean;
  13335. begin
  13336. Result := False;
  13337. { All these optimisations work on "shr const,%reg" }
  13338. if not MatchOpType(taicpu(p), top_const, top_reg) then
  13339. Exit;
  13340. DoNotMerge := False;
  13341. Shift := taicpu(p).oper[0]^.val;
  13342. LimitSize := taicpu(p).opsize;
  13343. hp1 := p;
  13344. repeat
  13345. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  13346. Break;
  13347. { Detect:
  13348. shr x, %reg
  13349. and y, %reg
  13350. If and y, %reg doesn't actually change the value of %reg (e.g. with
  13351. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  13352. }
  13353. case taicpu(hp1).opcode of
  13354. A_AND:
  13355. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  13356. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13357. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  13358. begin
  13359. { Make sure the FLAGS register isn't in use }
  13360. TransferUsedRegs(TmpUsedRegs);
  13361. hp2 := p;
  13362. repeat
  13363. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  13364. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  13365. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  13366. begin
  13367. { Generate the identity mask }
  13368. case taicpu(p).opsize of
  13369. S_B:
  13370. IdentityMask := $FF shr Shift;
  13371. S_W:
  13372. IdentityMask := $FFFF shr Shift;
  13373. S_L:
  13374. IdentityMask := $FFFFFFFF shr Shift;
  13375. {$ifdef x86_64}
  13376. S_Q:
  13377. { We need to force the operands to be unsigned 64-bit
  13378. integers otherwise the wrong value is generated }
  13379. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  13380. {$endif x86_64}
  13381. else
  13382. InternalError(2022081501);
  13383. end;
  13384. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  13385. begin
  13386. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  13387. { All the possible 1 bits are covered, so we can remove the AND }
  13388. hp2 := tai(hp1.Previous);
  13389. RemoveInstruction(hp1);
  13390. { p wasn't actually changed, so don't set Result to True,
  13391. but a change was nonetheless made elsewhere }
  13392. Include(OptsToCheck, aoc_ForceNewIteration);
  13393. { Do another pass in case other AND or MOVZX instructions
  13394. follow }
  13395. hp1 := hp2;
  13396. Continue;
  13397. end;
  13398. end;
  13399. end;
  13400. A_TEST, A_CMP, A_Jcc:
  13401. { Skip over conditional jumps and relevant comparisons }
  13402. Continue;
  13403. A_MOVZX:
  13404. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13405. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  13406. begin
  13407. { Since the original register is being read as is, subsequent
  13408. SHRs must not be merged at this point }
  13409. DoNotMerge := True;
  13410. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  13411. begin
  13412. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  13413. begin
  13414. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  13415. { All the possible 1 bits are covered, so we can remove the AND }
  13416. hp2 := tai(hp1.Previous);
  13417. RemoveInstruction(hp1);
  13418. hp1 := hp2;
  13419. end
  13420. else { Different register target }
  13421. begin
  13422. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  13423. taicpu(hp1).opcode := A_MOV;
  13424. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  13425. case taicpu(hp1).opsize of
  13426. S_BW:
  13427. taicpu(hp1).opsize := S_W;
  13428. S_BL, S_WL:
  13429. taicpu(hp1).opsize := S_L;
  13430. else
  13431. InternalError(2022081503);
  13432. end;
  13433. end;
  13434. end
  13435. else if (Shift > 0) and
  13436. (taicpu(p).opsize = S_W) and
  13437. (taicpu(hp1).opsize = S_WL) and
  13438. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  13439. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  13440. begin
  13441. { Detect:
  13442. shr x, %ax (x > 0)
  13443. ...
  13444. movzwl %ax,%eax
  13445. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  13446. }
  13447. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  13448. taicpu(hp1).opcode := A_CWDE;
  13449. taicpu(hp1).clearop(0);
  13450. taicpu(hp1).clearop(1);
  13451. taicpu(hp1).ops := 0;
  13452. end;
  13453. { Move onto the next instruction }
  13454. Continue;
  13455. end;
  13456. A_SHL, A_SAL, A_SHR:
  13457. if (taicpu(hp1).opsize <= LimitSize) and
  13458. MatchOpType(taicpu(hp1), top_const, top_reg) and
  13459. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  13460. begin
  13461. { Make sure the sizes don't exceed the register size limit
  13462. (measured by the shift value falling below the limit) }
  13463. if taicpu(hp1).opsize < LimitSize then
  13464. LimitSize := taicpu(hp1).opsize;
  13465. if taicpu(hp1).opcode = A_SHR then
  13466. Inc(Shift, taicpu(hp1).oper[0]^.val)
  13467. else
  13468. begin
  13469. Dec(Shift, taicpu(hp1).oper[0]^.val);
  13470. DoNotMerge := True;
  13471. end;
  13472. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  13473. Break;
  13474. { Since we've established that the combined shift is within
  13475. limits, we can actually combine the adjacent SHR
  13476. instructions even if they're different sizes }
  13477. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  13478. begin
  13479. hp2 := tai(hp1.Previous);
  13480. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  13481. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  13482. RemoveInstruction(hp1);
  13483. hp1 := hp2;
  13484. end;
  13485. { Move onto the next instruction }
  13486. Continue;
  13487. end;
  13488. else
  13489. ;
  13490. end;
  13491. Break;
  13492. until False;
  13493. { Detect the following (looking backwards):
  13494. shr %cl,%reg
  13495. shr x, %reg
  13496. Swap the two SHR instructions to minimise a pipeline stall.
  13497. }
  13498. if GetLastInstruction(p, hp1) and
  13499. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  13500. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  13501. { First operand will be %cl }
  13502. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  13503. { Just to be sure }
  13504. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  13505. begin
  13506. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  13507. { Moving the entries this way ensures the register tracking remains correct }
  13508. Asml.Remove(p);
  13509. Asml.InsertBefore(p, hp1);
  13510. p := hp1;
  13511. { Don't set Result to True because the current instruction is now
  13512. "shr %cl,%reg" and there's nothing more we can do with it }
  13513. end;
  13514. end;
  13515. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  13516. var
  13517. hp1, hp2: tai;
  13518. Opposite, SecondOpposite: TAsmOp;
  13519. NewCond: TAsmCond;
  13520. begin
  13521. Result := False;
  13522. { Change:
  13523. add/sub 128,(dest)
  13524. To:
  13525. sub/add -128,(dest)
  13526. This generaally takes fewer bytes to encode because -128 can be stored
  13527. in a signed byte, whereas +128 cannot.
  13528. }
  13529. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  13530. begin
  13531. if taicpu(p).opcode = A_ADD then
  13532. Opposite := A_SUB
  13533. else
  13534. Opposite := A_ADD;
  13535. { Be careful if the flags are in use, because the CF flag inverts
  13536. when changing from ADD to SUB and vice versa }
  13537. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  13538. GetNextInstruction(p, hp1) then
  13539. begin
  13540. TransferUsedRegs(TmpUsedRegs);
  13541. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  13542. hp2 := hp1;
  13543. { Scan ahead to check if everything's safe }
  13544. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  13545. begin
  13546. if (hp1.typ <> ait_instruction) then
  13547. { Probably unsafe since the flags are still in use }
  13548. Exit;
  13549. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  13550. { Stop searching at an unconditional jump }
  13551. Break;
  13552. if not
  13553. (
  13554. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  13555. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  13556. ) and
  13557. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  13558. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  13559. Exit;
  13560. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13561. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  13562. { Move to the next instruction }
  13563. GetNextInstruction(hp1, hp1);
  13564. end;
  13565. while Assigned(hp2) and (hp2 <> hp1) do
  13566. begin
  13567. NewCond := C_None;
  13568. case taicpu(hp2).condition of
  13569. C_A, C_NBE:
  13570. NewCond := C_BE;
  13571. C_B, C_C, C_NAE:
  13572. NewCond := C_AE;
  13573. C_AE, C_NB, C_NC:
  13574. NewCond := C_B;
  13575. C_BE, C_NA:
  13576. NewCond := C_A;
  13577. else
  13578. { No change needed };
  13579. end;
  13580. if NewCond <> C_None then
  13581. begin
  13582. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  13583. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  13584. taicpu(hp2).condition := NewCond;
  13585. end
  13586. else
  13587. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  13588. begin
  13589. { Because of the flipping of the carry bit, to ensure
  13590. the operation remains equivalent, ADC becomes SBB
  13591. and vice versa, and the constant is not-inverted.
  13592. If multiple ADCs or SBBs appear in a row, each one
  13593. changed causes the carry bit to invert, so they all
  13594. need to be flipped }
  13595. if taicpu(hp2).opcode = A_ADC then
  13596. SecondOpposite := A_SBB
  13597. else
  13598. SecondOpposite := A_ADC;
  13599. if taicpu(hp2).oper[0]^.typ <> top_const then
  13600. { Should have broken out of this optimisation already }
  13601. InternalError(2021112901);
  13602. 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]^) + ' -> ' +
  13603. 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);
  13604. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  13605. taicpu(hp2).opcode := SecondOpposite;
  13606. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  13607. end;
  13608. { Move to the next instruction }
  13609. GetNextInstruction(hp2, hp2);
  13610. end;
  13611. if (hp2 <> hp1) then
  13612. InternalError(2021111501);
  13613. end;
  13614. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  13615. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  13616. taicpu(p).opcode := Opposite;
  13617. taicpu(p).oper[0]^.val := -128;
  13618. { No further optimisations can be made on this instruction, so move
  13619. onto the next one to save time }
  13620. p := tai(p.Next);
  13621. UpdateUsedRegs(p);
  13622. Result := True;
  13623. Exit;
  13624. end;
  13625. { Detect:
  13626. add/sub %reg2,(dest)
  13627. add/sub x, (dest)
  13628. (dest can be a register or a reference)
  13629. Swap the instructions to minimise a pipeline stall. This reverses the
  13630. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  13631. optimisations could be made.
  13632. }
  13633. if (taicpu(p).oper[0]^.typ = top_reg) and
  13634. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  13635. (
  13636. (
  13637. (taicpu(p).oper[1]^.typ = top_reg) and
  13638. { We can try searching further ahead if we're writing to a register }
  13639. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  13640. ) or
  13641. (
  13642. (taicpu(p).oper[1]^.typ = top_ref) and
  13643. GetNextInstruction(p, hp1)
  13644. )
  13645. ) and
  13646. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  13647. (taicpu(hp1).oper[0]^.typ = top_const) and
  13648. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  13649. begin
  13650. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  13651. TransferUsedRegs(TmpUsedRegs);
  13652. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  13653. hp2 := p;
  13654. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  13655. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  13656. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  13657. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13658. begin
  13659. asml.remove(hp1);
  13660. asml.InsertBefore(hp1, p);
  13661. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  13662. Result := True;
  13663. end;
  13664. end;
  13665. end;
  13666. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  13667. var
  13668. hp1: tai;
  13669. begin
  13670. Result:=false;
  13671. { Final check to see if CMP/MOV pairs can be changed to MOV/CMP }
  13672. while GetNextInstruction(p, hp1) and
  13673. TrySwapMovCmp(p, hp1) do
  13674. begin
  13675. if MatchInstruction(hp1, A_MOV, []) then
  13676. begin
  13677. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13678. begin
  13679. { A little hacky, but since CMP doesn't read the flags, only
  13680. modify them, it's safe if they get scrambled by MOV -> XOR }
  13681. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13682. Result := PostPeepholeOptMov(hp1);
  13683. {$ifdef x86_64}
  13684. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13685. { Used to shrink instruction size }
  13686. PostPeepholeOptXor(hp1);
  13687. {$endif x86_64}
  13688. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13689. end
  13690. else
  13691. begin
  13692. Result := PostPeepholeOptMov(hp1);
  13693. {$ifdef x86_64}
  13694. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13695. { Used to shrink instruction size }
  13696. PostPeepholeOptXor(hp1);
  13697. {$endif x86_64}
  13698. end;
  13699. end;
  13700. { Enabling this flag is actually a null operation, but it marks
  13701. the code as 'modified' during this pass }
  13702. Include(OptsToCheck, aoc_ForceNewIteration);
  13703. end;
  13704. { change "cmp $0, %reg" to "test %reg, %reg" }
  13705. if MatchOpType(taicpu(p),top_const,top_reg) and
  13706. (taicpu(p).oper[0]^.val = 0) then
  13707. begin
  13708. taicpu(p).opcode := A_TEST;
  13709. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  13710. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  13711. Result:=true;
  13712. end;
  13713. end;
  13714. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  13715. var
  13716. IsTestConstX, IsValid : Boolean;
  13717. hp1,hp2 : tai;
  13718. begin
  13719. Result:=false;
  13720. { Final check to see if TEST/MOV pairs can be changed to MOV/TEST }
  13721. if (taicpu(p).opcode = A_TEST) then
  13722. while GetNextInstruction(p, hp1) and
  13723. TrySwapMovCmp(p, hp1) do
  13724. begin
  13725. if MatchInstruction(hp1, A_MOV, []) then
  13726. begin
  13727. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  13728. begin
  13729. { A little hacky, but since TEST doesn't read the flags, only
  13730. modify them, it's safe if they get scrambled by MOV -> XOR }
  13731. ExcludeRegFromUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13732. Result := PostPeepholeOptMov(hp1);
  13733. {$ifdef x86_64}
  13734. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13735. { Used to shrink instruction size }
  13736. PostPeepholeOptXor(hp1);
  13737. {$endif x86_64}
  13738. IncludeRegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs);
  13739. end
  13740. else
  13741. begin
  13742. Result := PostPeepholeOptMov(hp1);
  13743. {$ifdef x86_64}
  13744. if Result and MatchInstruction(hp1, A_XOR, [S_Q]) then
  13745. { Used to shrink instruction size }
  13746. PostPeepholeOptXor(hp1);
  13747. {$endif x86_64}
  13748. end;
  13749. end;
  13750. { Enabling this flag is actually a null operation, but it marks
  13751. the code as 'modified' during this pass }
  13752. Include(OptsToCheck, aoc_ForceNewIteration);
  13753. end;
  13754. { If x is a power of 2 (popcnt = 1), change:
  13755. or $x, %reg/ref
  13756. To:
  13757. bts lb(x), %reg/ref
  13758. }
  13759. if (taicpu(p).opcode = A_OR) and
  13760. IsBTXAcceptable(p) and
  13761. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  13762. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13763. (
  13764. { Don't optimise if a test instruction follows }
  13765. not GetNextInstruction(p, hp1) or
  13766. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  13767. ) then
  13768. begin
  13769. DebugMsg(SPeepholeOptimization + 'Changed OR $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BTS $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Or2Bts)', p);
  13770. taicpu(p).opcode := A_BTS;
  13771. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  13772. Result := True;
  13773. Exit;
  13774. end;
  13775. { If x is a power of 2 (popcnt = 1), change:
  13776. test $x, %reg/ref
  13777. je / sete / cmove (or jne / setne)
  13778. To:
  13779. bt lb(x), %reg/ref
  13780. jnc / setnc / cmovnc (or jc / setc / cmovnc)
  13781. }
  13782. if (taicpu(p).opcode = A_TEST) and
  13783. (CPUX86_HAS_BTX in cpu_capabilities[current_settings.optimizecputype]) and
  13784. (taicpu(p).oper[0]^.typ = top_const) and
  13785. (
  13786. (cs_opt_size in current_settings.optimizerswitches) or
  13787. (
  13788. (taicpu(p).oper[1]^.typ = top_reg) and
  13789. (CPUX86_HINT_FAST_BT_REG_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  13790. ) or
  13791. (
  13792. (taicpu(p).oper[1]^.typ <> top_reg) and
  13793. (CPUX86_HINT_FAST_BT_MEM_IMM in cpu_optimization_hints[current_settings.optimizecputype])
  13794. )
  13795. ) and
  13796. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  13797. { For sizes less than S_L, the byte size is equal or larger with BT,
  13798. so don't bother optimising }
  13799. (taicpu(p).opsize >= S_L) then
  13800. begin
  13801. IsValid := True;
  13802. { Check the next set of instructions, watching the FLAGS register
  13803. and the conditions used }
  13804. TransferUsedRegs(TmpUsedRegs);
  13805. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  13806. hp1 := p;
  13807. hp2 := nil;
  13808. while GetNextInstruction(hp1, hp1) do
  13809. begin
  13810. if not Assigned(hp2) then
  13811. { The first instruction after TEST }
  13812. hp2 := hp1;
  13813. if (hp1.typ <> ait_instruction) then
  13814. begin
  13815. { If the flags are no longer in use, everything is fine }
  13816. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13817. IsValid := False;
  13818. Break;
  13819. end;
  13820. case taicpu(hp1).condition of
  13821. C_None:
  13822. begin
  13823. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  13824. { Something is not quite normal, so play safe and don't change }
  13825. IsValid := False;
  13826. Break;
  13827. end;
  13828. C_E, C_Z, C_NE, C_NZ:
  13829. { This is fine };
  13830. else
  13831. begin
  13832. { Unsupported condition }
  13833. IsValid := False;
  13834. Break;
  13835. end;
  13836. end;
  13837. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  13838. end;
  13839. if IsValid then
  13840. begin
  13841. while hp2 <> hp1 do
  13842. begin
  13843. case taicpu(hp2).condition of
  13844. C_Z, C_E:
  13845. taicpu(hp2).condition := C_NC;
  13846. C_NZ, C_NE:
  13847. taicpu(hp2).condition := C_C;
  13848. else
  13849. { Should not get this by this point }
  13850. InternalError(2022110701);
  13851. end;
  13852. GetNextInstruction(hp2, hp2);
  13853. end;
  13854. DebugMsg(SPeepholeOptimization + 'Changed TEST $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BT $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Test2Bt)', p);
  13855. taicpu(p).opcode := A_BT;
  13856. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  13857. Result := True;
  13858. Exit;
  13859. end;
  13860. end;
  13861. { removes the line marked with (x) from the sequence
  13862. and/or/xor/add/sub/... $x, %y
  13863. test/or %y, %y | test $-1, %y (x)
  13864. j(n)z _Label
  13865. as the first instruction already adjusts the ZF
  13866. %y operand may also be a reference }
  13867. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  13868. MatchOperand(taicpu(p).oper[0]^,-1);
  13869. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  13870. GetLastInstruction(p, hp1) and
  13871. (tai(hp1).typ = ait_instruction) and
  13872. GetNextInstruction(p,hp2) and
  13873. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  13874. case taicpu(hp1).opcode Of
  13875. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  13876. { These two instructions set the zero flag if the result is zero }
  13877. A_POPCNT, A_LZCNT:
  13878. begin
  13879. if (
  13880. { With POPCNT, an input of zero will set the zero flag
  13881. because the population count of zero is zero }
  13882. (taicpu(hp1).opcode = A_POPCNT) and
  13883. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  13884. (
  13885. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  13886. { Faster than going through the second half of the 'or'
  13887. condition below }
  13888. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  13889. )
  13890. ) or (
  13891. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  13892. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  13893. { and in case of carry for A(E)/B(E)/C/NC }
  13894. (
  13895. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  13896. (
  13897. (taicpu(hp1).opcode <> A_ADD) and
  13898. (taicpu(hp1).opcode <> A_SUB) and
  13899. (taicpu(hp1).opcode <> A_LZCNT)
  13900. )
  13901. )
  13902. ) then
  13903. begin
  13904. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  13905. RemoveCurrentP(p, hp2);
  13906. Result:=true;
  13907. Exit;
  13908. end;
  13909. end;
  13910. A_SHL, A_SAL, A_SHR, A_SAR:
  13911. begin
  13912. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  13913. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  13914. { therefore, it's only safe to do this optimization for }
  13915. { shifts by a (nonzero) constant }
  13916. (taicpu(hp1).oper[0]^.typ = top_const) and
  13917. (taicpu(hp1).oper[0]^.val <> 0) and
  13918. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  13919. { and in case of carry for A(E)/B(E)/C/NC }
  13920. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  13921. begin
  13922. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  13923. RemoveCurrentP(p, hp2);
  13924. Result:=true;
  13925. Exit;
  13926. end;
  13927. end;
  13928. A_DEC, A_INC, A_NEG:
  13929. begin
  13930. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  13931. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  13932. { and in case of carry for A(E)/B(E)/C/NC }
  13933. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  13934. begin
  13935. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  13936. RemoveCurrentP(p, hp2);
  13937. Result:=true;
  13938. Exit;
  13939. end;
  13940. end;
  13941. A_ANDN, A_BZHI:
  13942. begin
  13943. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  13944. { Only the zero and sign flags are consistent with what the result is }
  13945. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  13946. begin
  13947. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  13948. RemoveCurrentP(p, hp2);
  13949. Result:=true;
  13950. Exit;
  13951. end;
  13952. end;
  13953. A_BEXTR:
  13954. begin
  13955. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  13956. { Only the zero flag is set }
  13957. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  13958. begin
  13959. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  13960. RemoveCurrentP(p, hp2);
  13961. Result:=true;
  13962. Exit;
  13963. end;
  13964. end;
  13965. else
  13966. ;
  13967. end; { case }
  13968. { change "test $-1,%reg" into "test %reg,%reg" }
  13969. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  13970. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  13971. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  13972. if MatchInstruction(p, A_OR, []) and
  13973. { Can only match if they're both registers }
  13974. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  13975. begin
  13976. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  13977. taicpu(p).opcode := A_TEST;
  13978. { No need to set Result to True, as we've done all the optimisations we can }
  13979. end;
  13980. end;
  13981. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  13982. var
  13983. hp1,hp3 : tai;
  13984. {$ifndef x86_64}
  13985. hp2 : taicpu;
  13986. {$endif x86_64}
  13987. begin
  13988. Result:=false;
  13989. hp3:=nil;
  13990. {$ifndef x86_64}
  13991. { don't do this on modern CPUs, this really hurts them due to
  13992. broken call/ret pairing }
  13993. if (current_settings.optimizecputype < cpu_Pentium2) and
  13994. not(cs_create_pic in current_settings.moduleswitches) and
  13995. GetNextInstruction(p, hp1) and
  13996. MatchInstruction(hp1,A_JMP,[S_NO]) and
  13997. MatchOpType(taicpu(hp1),top_ref) and
  13998. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  13999. begin
  14000. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  14001. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  14002. InsertLLItem(p.previous, p, hp2);
  14003. taicpu(p).opcode := A_JMP;
  14004. taicpu(p).is_jmp := true;
  14005. RemoveInstruction(hp1);
  14006. Result:=true;
  14007. end
  14008. else
  14009. {$endif x86_64}
  14010. { replace
  14011. call procname
  14012. ret
  14013. by
  14014. jmp procname
  14015. but do it only on level 4 because it destroys stack back traces
  14016. else if the subroutine is marked as no return, remove the ret
  14017. }
  14018. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  14019. (po_noreturn in current_procinfo.procdef.procoptions)) and
  14020. GetNextInstruction(p, hp1) and
  14021. (MatchInstruction(hp1,A_RET,[S_NO]) or
  14022. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  14023. SetAndTest(hp1,hp3) and
  14024. GetNextInstruction(hp1,hp1) and
  14025. MatchInstruction(hp1,A_RET,[S_NO])
  14026. )
  14027. ) and
  14028. (taicpu(hp1).ops=0) then
  14029. begin
  14030. if (cs_opt_level4 in current_settings.optimizerswitches) and
  14031. { we might destroy stack alignment here if we do not do a call }
  14032. (target_info.stackalign<=sizeof(SizeUInt)) then
  14033. begin
  14034. taicpu(p).opcode := A_JMP;
  14035. taicpu(p).is_jmp := true;
  14036. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  14037. end
  14038. else
  14039. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  14040. RemoveInstruction(hp1);
  14041. if Assigned(hp3) then
  14042. begin
  14043. AsmL.Remove(hp3);
  14044. AsmL.InsertBefore(hp3,p)
  14045. end;
  14046. Result:=true;
  14047. end;
  14048. end;
  14049. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  14050. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  14051. begin
  14052. case OpSize of
  14053. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  14054. Result := (Val <= $FF) and (Val >= -128);
  14055. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  14056. Result := (Val <= $FFFF) and (Val >= -32768);
  14057. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  14058. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  14059. else
  14060. Result := True;
  14061. end;
  14062. end;
  14063. var
  14064. hp1, hp2 : tai;
  14065. SizeChange: Boolean;
  14066. PreMessage: string;
  14067. begin
  14068. Result := False;
  14069. if (taicpu(p).oper[0]^.typ = top_reg) and
  14070. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  14071. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  14072. begin
  14073. { Change (using movzbl %al,%eax as an example):
  14074. movzbl %al, %eax movzbl %al, %eax
  14075. cmpl x, %eax testl %eax,%eax
  14076. To:
  14077. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  14078. movzbl %al, %eax movzbl %al, %eax
  14079. Smaller instruction and minimises pipeline stall as the CPU
  14080. doesn't have to wait for the register to get zero-extended. [Kit]
  14081. Also allow if the smaller of the two registers is being checked,
  14082. as this still removes the false dependency.
  14083. }
  14084. if
  14085. (
  14086. (
  14087. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  14088. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  14089. ) or (
  14090. { If MatchOperand returns True, they must both be registers }
  14091. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  14092. )
  14093. ) and
  14094. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  14095. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  14096. begin
  14097. 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);
  14098. asml.Remove(hp1);
  14099. asml.InsertBefore(hp1, p);
  14100. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  14101. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  14102. begin
  14103. taicpu(hp1).opcode := A_TEST;
  14104. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  14105. end;
  14106. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  14107. case taicpu(p).opsize of
  14108. S_BW, S_BL:
  14109. begin
  14110. SizeChange := taicpu(hp1).opsize <> S_B;
  14111. taicpu(hp1).changeopsize(S_B);
  14112. end;
  14113. S_WL:
  14114. begin
  14115. SizeChange := taicpu(hp1).opsize <> S_W;
  14116. taicpu(hp1).changeopsize(S_W);
  14117. end
  14118. else
  14119. InternalError(2020112701);
  14120. end;
  14121. UpdateUsedRegs(tai(p.Next));
  14122. { Check if the register is used aferwards - if not, we can
  14123. remove the movzx instruction completely }
  14124. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  14125. begin
  14126. { Hp1 is a better position than p for debugging purposes }
  14127. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  14128. RemoveCurrentp(p, hp1);
  14129. Result := True;
  14130. end;
  14131. if SizeChange then
  14132. DebugMsg(SPeepholeOptimization + PreMessage +
  14133. 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)
  14134. else
  14135. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  14136. Exit;
  14137. end;
  14138. { Change (using movzwl %ax,%eax as an example):
  14139. movzwl %ax, %eax
  14140. movb %al, (dest) (Register is smaller than read register in movz)
  14141. To:
  14142. movb %al, (dest) (Move one back to avoid a false dependency)
  14143. movzwl %ax, %eax
  14144. }
  14145. if (taicpu(hp1).opcode = A_MOV) and
  14146. (taicpu(hp1).oper[0]^.typ = top_reg) and
  14147. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  14148. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  14149. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  14150. begin
  14151. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  14152. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  14153. asml.Remove(hp1);
  14154. asml.InsertBefore(hp1, p);
  14155. if taicpu(hp1).oper[1]^.typ = top_reg then
  14156. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  14157. { Check if the register is used aferwards - if not, we can
  14158. remove the movzx instruction completely }
  14159. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  14160. begin
  14161. { Hp1 is a better position than p for debugging purposes }
  14162. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  14163. RemoveCurrentp(p, hp1);
  14164. Result := True;
  14165. end;
  14166. Exit;
  14167. end;
  14168. end;
  14169. end;
  14170. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  14171. var
  14172. hp1: tai;
  14173. {$ifdef x86_64}
  14174. PreMessage, RegName: string;
  14175. {$endif x86_64}
  14176. begin
  14177. Result := False;
  14178. { If x is a power of 2 (popcnt = 1), change:
  14179. xor $x, %reg/ref
  14180. To:
  14181. btc lb(x), %reg/ref
  14182. }
  14183. if IsBTXAcceptable(p) and
  14184. { IsBTXAcceptable checks to see if oper[0] is an immediate }
  14185. (PopCnt(QWord(taicpu(p).oper[0]^.val)) = 1) and
  14186. (
  14187. { Don't optimise if a test instruction follows }
  14188. not GetNextInstruction(p, hp1) or
  14189. not MatchInstruction(hp1, A_TEST, [taicpu(p).opsize])
  14190. ) then
  14191. begin
  14192. DebugMsg(SPeepholeOptimization + 'Changed XOR $' + debug_hexstr(taicpu(p).oper[0]^.val) + ' to BTC $' + debug_tostr(BsrQWord(taicpu(p).oper[0]^.val)) + ' to shrink instruction size (Xor2Btc)', p);
  14193. taicpu(p).opcode := A_BTC;
  14194. taicpu(p).oper[0]^.val := BsrQWord(taicpu(p).oper[0]^.val); { Essentially the base 2 logarithm }
  14195. Result := True;
  14196. Exit;
  14197. end;
  14198. {$ifdef x86_64}
  14199. { Code size reduction by J. Gareth "Kit" Moreton }
  14200. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  14201. as this removes the REX prefix }
  14202. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  14203. Exit;
  14204. if taicpu(p).oper[0]^.typ <> top_reg then
  14205. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  14206. InternalError(2018011500);
  14207. case taicpu(p).opsize of
  14208. S_Q:
  14209. begin
  14210. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  14211. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  14212. { The actual optimization }
  14213. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  14214. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  14215. taicpu(p).changeopsize(S_L);
  14216. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  14217. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  14218. end;
  14219. else
  14220. ;
  14221. end;
  14222. {$endif x86_64}
  14223. end;
  14224. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  14225. var
  14226. XReg: TRegister;
  14227. begin
  14228. Result := False;
  14229. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  14230. Smaller encoding and slightly faster on some platforms (also works for
  14231. ZMM-sized registers) }
  14232. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  14233. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  14234. begin
  14235. XReg := taicpu(p).oper[0]^.reg;
  14236. if (taicpu(p).oper[1]^.reg = XReg) then
  14237. begin
  14238. taicpu(p).changeopsize(S_XMM);
  14239. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  14240. if (cs_opt_size in current_settings.optimizerswitches) then
  14241. begin
  14242. { Change input registers to %xmm0 to reduce size. Note that
  14243. there's a risk of a false dependency doing this, so only
  14244. optimise for size here }
  14245. XReg := NR_XMM0;
  14246. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  14247. end
  14248. else
  14249. begin
  14250. setsubreg(XReg, R_SUBMMX);
  14251. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  14252. end;
  14253. taicpu(p).oper[0]^.reg := XReg;
  14254. taicpu(p).oper[1]^.reg := XReg;
  14255. Result := True;
  14256. end;
  14257. end;
  14258. end;
  14259. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  14260. var
  14261. OperIdx: Integer;
  14262. begin
  14263. for OperIdx := 0 to p.ops - 1 do
  14264. if p.oper[OperIdx]^.typ = top_ref then
  14265. optimize_ref(p.oper[OperIdx]^.ref^, False);
  14266. end;
  14267. end.