aoptx86.pas 618 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464
  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): 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): TRegister;
  83. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  84. class function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean; static;
  85. { checks whether reading the value in reg1 depends on the value of reg2. This
  86. is very similar to SuperRegisterEquals, except it takes into account that
  87. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  88. depend on the value in AH). }
  89. class function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean; static;
  90. { Replaces all references to AOldReg in a memory reference to ANewReg }
  91. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  92. { Replaces all references to AOldReg in an operand to ANewReg }
  93. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  94. { Replaces all references to AOldReg in an instruction to ANewReg,
  95. except where the register is being written }
  96. class function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean; static;
  97. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  98. or writes to a global symbol }
  99. class function IsRefSafe(const ref: PReference): Boolean; static;
  100. { Returns true if the given MOV instruction can be safely converted to CMOV }
  101. class function CanBeCMOV(p : tai) : boolean; static;
  102. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  103. conversion was successful }
  104. function ConvertLEA(const p : taicpu): Boolean;
  105. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  106. function FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  107. procedure DebugMsg(const s : string; p : tai);inline;
  108. class function IsExitCode(p : tai) : boolean; static;
  109. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  110. class function IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean; static;
  111. procedure RemoveLastDeallocForFuncRes(p : tai);
  112. function DoArithCombineOpt(var p : tai) : Boolean;
  113. function DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  114. function DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  115. function PrePeepholeOptSxx(var p : tai) : boolean;
  116. function PrePeepholeOptIMUL(var p : tai) : boolean;
  117. function PrePeepholeOptAND(var p : tai) : boolean;
  118. function OptPass1Test(var p: tai): boolean;
  119. function OptPass1Add(var p: tai): boolean;
  120. function OptPass1AND(var p : tai) : boolean;
  121. function OptPass1_V_MOVAP(var p : tai) : boolean;
  122. function OptPass1VOP(var p : tai) : boolean;
  123. function OptPass1MOV(var p : tai) : boolean;
  124. function OptPass1Movx(var p : tai) : boolean;
  125. function OptPass1MOVXX(var p : tai) : boolean;
  126. function OptPass1OP(var p : tai) : boolean;
  127. function OptPass1LEA(var p : tai) : boolean;
  128. function OptPass1Sub(var p : tai) : boolean;
  129. function OptPass1SHLSAL(var p : tai) : boolean;
  130. function OptPass1SHR(var p : tai) : boolean;
  131. function OptPass1FSTP(var p : tai) : boolean;
  132. function OptPass1FLD(var p : tai) : boolean;
  133. function OptPass1Cmp(var p : tai) : boolean;
  134. function OptPass1PXor(var p : tai) : boolean;
  135. function OptPass1VPXor(var p: tai): boolean;
  136. function OptPass1Imul(var p : tai) : boolean;
  137. function OptPass1Jcc(var p : tai) : boolean;
  138. function OptPass1SHXX(var p: tai): boolean;
  139. function OptPass1VMOVDQ(var p: tai): Boolean;
  140. function OptPass1_V_Cvtss2sd(var p: tai): boolean;
  141. function OptPass2Movx(var p : tai): Boolean;
  142. function OptPass2MOV(var p : tai) : boolean;
  143. function OptPass2Imul(var p : tai) : boolean;
  144. function OptPass2Jmp(var p : tai) : boolean;
  145. function OptPass2Jcc(var p : tai) : boolean;
  146. function OptPass2Lea(var p: tai): Boolean;
  147. function OptPass2SUB(var p: tai): Boolean;
  148. function OptPass2ADD(var p : tai): Boolean;
  149. function OptPass2SETcc(var p : tai) : boolean;
  150. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  151. function PostPeepholeOptMov(var p : tai) : Boolean;
  152. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  153. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  154. function PostPeepholeOptXor(var p : tai) : Boolean;
  155. {$endif x86_64}
  156. function PostPeepholeOptAnd(var p : tai) : boolean;
  157. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  158. function PostPeepholeOptCmp(var p : tai) : Boolean;
  159. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  160. function PostPeepholeOptCall(var p : tai) : Boolean;
  161. function PostPeepholeOptLea(var p : tai) : Boolean;
  162. function PostPeepholeOptPush(var p: tai): Boolean;
  163. function PostPeepholeOptShr(var p : tai) : boolean;
  164. function PostPeepholeOptADDSUB(var p : tai) : Boolean;
  165. function PostPeepholeOptVPXOR(var p: tai): Boolean;
  166. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  167. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  168. function TrySwapMovCmp(var p, hp1: tai): Boolean;
  169. { Processor-dependent reference optimisation }
  170. class procedure OptimizeRefs(var p: taicpu); static;
  171. end;
  172. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  173. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  174. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  175. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  176. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  177. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  178. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  179. {$if max_operands>2}
  180. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  181. {$endif max_operands>2}
  182. function RefsEqual(const r1, r2: treference): boolean;
  183. { Note that Result is set to True if the references COULD overlap but the
  184. compiler cannot be sure (e.g. "(%reg1)" and "4(%reg2)" with a range of 4
  185. might still overlap because %reg2 could be equal to %reg1-4 }
  186. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  187. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  188. { returns true, if ref is a reference using only the registers passed as base and index
  189. and having an offset }
  190. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  191. implementation
  192. uses
  193. cutils,verbose,
  194. systems,
  195. globals,
  196. cpuinfo,
  197. procinfo,
  198. paramgr,
  199. aasmbase,
  200. aoptbase,aoptutils,
  201. symconst,symsym,
  202. cgx86,
  203. itcpugas;
  204. {$ifdef DEBUG_AOPTCPU}
  205. const
  206. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  207. {$else DEBUG_AOPTCPU}
  208. { Empty strings help the optimizer to remove string concatenations that won't
  209. ever appear to the user on release builds. [Kit] }
  210. const
  211. SPeepholeOptimization = '';
  212. {$endif DEBUG_AOPTCPU}
  213. LIST_STEP_SIZE = 4;
  214. type
  215. TJumpTrackingItem = class(TLinkedListItem)
  216. private
  217. FSymbol: TAsmSymbol;
  218. FRefs: LongInt;
  219. public
  220. constructor Create(ASymbol: TAsmSymbol);
  221. procedure IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  222. property Symbol: TAsmSymbol read FSymbol;
  223. property Refs: LongInt read FRefs;
  224. end;
  225. constructor TJumpTrackingItem.Create(ASymbol: TAsmSymbol);
  226. begin
  227. inherited Create;
  228. FSymbol := ASymbol;
  229. FRefs := 0;
  230. end;
  231. procedure TJumpTrackingItem.IncRefs; {$ifdef USEINLINE}inline;{$endif USEINLINE}
  232. begin
  233. Inc(FRefs);
  234. end;
  235. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  236. begin
  237. result :=
  238. (instr.typ = ait_instruction) and
  239. (taicpu(instr).opcode = op) and
  240. ((opsize = []) or (taicpu(instr).opsize in opsize));
  241. end;
  242. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  243. begin
  244. result :=
  245. (instr.typ = ait_instruction) and
  246. ((taicpu(instr).opcode = op1) or
  247. (taicpu(instr).opcode = op2)
  248. ) and
  249. ((opsize = []) or (taicpu(instr).opsize in opsize));
  250. end;
  251. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  252. begin
  253. result :=
  254. (instr.typ = ait_instruction) and
  255. ((taicpu(instr).opcode = op1) or
  256. (taicpu(instr).opcode = op2) or
  257. (taicpu(instr).opcode = op3)
  258. ) and
  259. ((opsize = []) or (taicpu(instr).opsize in opsize));
  260. end;
  261. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  262. const opsize : topsizes) : boolean;
  263. var
  264. op : TAsmOp;
  265. begin
  266. result:=false;
  267. if (instr.typ <> ait_instruction) or
  268. ((opsize <> []) and not(taicpu(instr).opsize in opsize)) then
  269. exit;
  270. for op in ops do
  271. begin
  272. if taicpu(instr).opcode = op then
  273. begin
  274. result:=true;
  275. exit;
  276. end;
  277. end;
  278. end;
  279. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  280. begin
  281. result := (oper.typ = top_reg) and (oper.reg = reg);
  282. end;
  283. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  284. begin
  285. result := (oper.typ = top_const) and (oper.val = a);
  286. end;
  287. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  288. begin
  289. result := oper1.typ = oper2.typ;
  290. if result then
  291. case oper1.typ of
  292. top_const:
  293. Result:=oper1.val = oper2.val;
  294. top_reg:
  295. Result:=oper1.reg = oper2.reg;
  296. top_ref:
  297. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  298. else
  299. internalerror(2013102801);
  300. end
  301. end;
  302. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  303. begin
  304. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  305. if result then
  306. case oper1.typ of
  307. top_const:
  308. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  309. top_reg:
  310. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  311. top_ref:
  312. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  313. else
  314. internalerror(2020052401);
  315. end
  316. end;
  317. function RefsEqual(const r1, r2: treference): boolean;
  318. begin
  319. RefsEqual :=
  320. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  321. (r1.relsymbol = r2.relsymbol) and
  322. (r1.segment = r2.segment) and (r1.base = r2.base) and
  323. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  324. (r1.offset = r2.offset) and
  325. (r1.volatility + r2.volatility = []);
  326. end;
  327. function RefsMightOverlap(const r1, r2: treference; const Range: asizeint): boolean;
  328. begin
  329. if (r1.symbol<>r2.symbol) then
  330. { If the index registers are different, there's a chance one could
  331. be set so it equals the other symbol }
  332. Exit((r1.index<>r2.index) or (r1.scalefactor<>r2.scalefactor));
  333. if (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  334. (r1.relsymbol = r2.relsymbol) and
  335. (r1.segment = r2.segment) and (r1.base = r2.base) and
  336. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  337. (r1.volatility + r2.volatility = []) then
  338. { In this case, it all depends on the offsets }
  339. Exit(abs(r1.offset - r2.offset) < Range);
  340. { There's a chance things MIGHT overlap, so take no chances }
  341. Result := True;
  342. end;
  343. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  344. begin
  345. Result:=(ref.offset=0) and
  346. (ref.scalefactor in [0,1]) and
  347. (ref.segment=NR_NO) and
  348. (ref.symbol=nil) and
  349. (ref.relsymbol=nil) and
  350. ((base=NR_INVALID) or
  351. (ref.base=base)) and
  352. ((index=NR_INVALID) or
  353. (ref.index=index)) and
  354. (ref.volatility=[]);
  355. end;
  356. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  357. begin
  358. Result:=(ref.scalefactor in [0,1]) and
  359. (ref.segment=NR_NO) and
  360. (ref.symbol=nil) and
  361. (ref.relsymbol=nil) and
  362. ((base=NR_INVALID) or
  363. (ref.base=base)) and
  364. ((index=NR_INVALID) or
  365. (ref.index=index)) and
  366. (ref.volatility=[]);
  367. end;
  368. function InstrReadsFlags(p: tai): boolean;
  369. begin
  370. InstrReadsFlags := true;
  371. case p.typ of
  372. ait_instruction:
  373. if InsProp[taicpu(p).opcode].Ch*
  374. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  375. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  376. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  377. exit;
  378. ait_label:
  379. exit;
  380. else
  381. ;
  382. end;
  383. InstrReadsFlags := false;
  384. end;
  385. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  386. begin
  387. Next:=Current;
  388. repeat
  389. Result:=GetNextInstruction(Next,Next);
  390. until not (Result) or
  391. not(cs_opt_level3 in current_settings.optimizerswitches) or
  392. (Next.typ<>ait_instruction) or
  393. RegInInstruction(reg,Next) or
  394. is_calljmp(taicpu(Next).opcode);
  395. end;
  396. function TX86AsmOptimizer.GetNextInstructionUsingRegCount(Current: tai; out Next: tai; reg: TRegister): Cardinal;
  397. var
  398. GetNextResult: Boolean;
  399. begin
  400. Result:=0;
  401. Next:=Current;
  402. repeat
  403. GetNextResult := GetNextInstruction(Next,Next);
  404. if GetNextResult then
  405. Inc(Result)
  406. else
  407. { Must return zero upon hitting the end of the linked list without a match }
  408. Result := 0;
  409. until not (GetNextResult) or
  410. not(cs_opt_level3 in current_settings.optimizerswitches) or
  411. (Next.typ<>ait_instruction) or
  412. RegInInstruction(reg,Next) or
  413. is_calljmp(taicpu(Next).opcode);
  414. end;
  415. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var JumpTracking: TLinkedList; var CrossJump: Boolean): Boolean;
  416. procedure TrackJump(Symbol: TAsmSymbol);
  417. var
  418. Search: TJumpTrackingItem;
  419. begin
  420. { See if an entry already exists in our jump tracking list
  421. (faster to search backwards due to the higher chance of
  422. matching destinations) }
  423. Search := TJumpTrackingItem(JumpTracking.Last);
  424. while Assigned(Search) do
  425. begin
  426. if Search.Symbol = Symbol then
  427. begin
  428. { Found it - remove it so it can be pushed to the front }
  429. JumpTracking.Remove(Search);
  430. Break;
  431. end;
  432. Search := TJumpTrackingItem(Search.Previous);
  433. end;
  434. if not Assigned(Search) then
  435. Search := TJumpTrackingItem.Create(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  436. JumpTracking.Concat(Search);
  437. Search.IncRefs;
  438. end;
  439. function LabelAccountedFor(Symbol: TAsmSymbol): Boolean;
  440. var
  441. Search: TJumpTrackingItem;
  442. begin
  443. Result := False;
  444. { See if this label appears in the tracking list }
  445. Search := TJumpTrackingItem(JumpTracking.Last);
  446. while Assigned(Search) do
  447. begin
  448. if Search.Symbol = Symbol then
  449. begin
  450. { Found it - let's see what we can discover }
  451. if Search.Symbol.getrefs = Search.Refs then
  452. begin
  453. { Success - all the references are accounted for }
  454. JumpTracking.Remove(Search);
  455. Search.Free;
  456. { It is logically impossible for CrossJump to be false here
  457. because we must have run into a conditional jump for
  458. this label at some point }
  459. if not CrossJump then
  460. InternalError(2022041710);
  461. if JumpTracking.First = nil then
  462. { Tracking list is now empty - no more cross jumps }
  463. CrossJump := False;
  464. Result := True;
  465. Exit;
  466. end;
  467. { If the references don't match, it's possible to enter
  468. this label through other means, so drop out }
  469. Exit;
  470. end;
  471. Search := TJumpTrackingItem(Search.Previous);
  472. end;
  473. end;
  474. var
  475. Next_Label: tai;
  476. begin
  477. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  478. Next := Current;
  479. repeat
  480. Result := GetNextInstruction(Next,Next);
  481. if not Result then
  482. Break;
  483. if Next.typ = ait_align then
  484. Result := SkipAligns(Next, Next);
  485. if (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  486. if is_calljmpuncondret(taicpu(Next).opcode) then
  487. begin
  488. if (taicpu(Next).opcode = A_JMP) and
  489. { Remove dead code now to save time }
  490. RemoveDeadCodeAfterJump(taicpu(Next)) then
  491. { A jump was removed, but not the current instruction, and
  492. Result doesn't necessarily translate into an optimisation
  493. routine's Result, so use the "Force New Iteration" flag so
  494. mark a new pass }
  495. Include(OptsToCheck, aoc_ForceNewIteration);
  496. if not Assigned(JumpTracking) then
  497. begin
  498. { Cross-label optimisations often causes other optimisations
  499. to perform worse because they're not given the chance to
  500. optimise locally. In this case, don't do the cross-label
  501. optimisations yet, but flag them as a potential possibility
  502. for the next iteration of Pass 1 }
  503. if not NotFirstIteration then
  504. Include(OptsToCheck, aoc_ForceNewIteration);
  505. end
  506. else if IsJumpToLabel(taicpu(Next)) and
  507. GetNextInstruction(Next, Next_Label) and
  508. SkipAligns(Next_Label, Next_Label) then
  509. begin
  510. { If we have JMP .lbl, and the label after it has all of its
  511. references tracked, then this is probably an if-else style of
  512. block and we can keep tracking. If the label for this jump
  513. then appears later and is fully tracked, then it's the end
  514. of the if-else blocks and the code paths converge (thus
  515. marking the end of the cross-jump) }
  516. if (Next_Label.typ = ait_label) then
  517. begin
  518. if LabelAccountedFor(tai_label(Next_Label).labsym) then
  519. begin
  520. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol);
  521. Next := Next_Label;
  522. { CrossJump gets set to false by LabelAccountedFor if the
  523. list is completely emptied (as it indicates that all
  524. code paths have converged). We could avoid this nuance
  525. by moving the TrackJump call to before the
  526. LabelAccountedFor call, but this is slower in situations
  527. where LabelAccountedFor would return False due to the
  528. creation of a new object that is not used and destroyed
  529. soon after. }
  530. CrossJump := True;
  531. Continue;
  532. end;
  533. end
  534. else if (Next_Label.typ <> ait_marker) then
  535. { We just did a RemoveDeadCodeAfterJump, so either we find
  536. a label, the end of the procedure or some kind of marker}
  537. InternalError(2022041720);
  538. end;
  539. Result := False;
  540. Exit;
  541. end
  542. else
  543. begin
  544. if not Assigned(JumpTracking) then
  545. begin
  546. { Cross-label optimisations often causes other optimisations
  547. to perform worse because they're not given the chance to
  548. optimise locally. In this case, don't do the cross-label
  549. optimisations yet, but flag them as a potential possibility
  550. for the next iteration of Pass 1 }
  551. if not NotFirstIteration then
  552. Include(OptsToCheck, aoc_ForceNewIteration);
  553. end
  554. else if IsJumpToLabel(taicpu(Next)) then
  555. TrackJump(JumpTargetOp(taicpu(Next))^.ref^.symbol)
  556. else
  557. { Conditional jumps should always be a jump to label }
  558. InternalError(2022041701);
  559. CrossJump := True;
  560. Continue;
  561. end;
  562. if Next.typ = ait_label then
  563. begin
  564. if not Assigned(JumpTracking) then
  565. begin
  566. { Cross-label optimisations often causes other optimisations
  567. to perform worse because they're not given the chance to
  568. optimise locally. In this case, don't do the cross-label
  569. optimisations yet, but flag them as a potential possibility
  570. for the next iteration of Pass 1 }
  571. if not NotFirstIteration then
  572. Include(OptsToCheck, aoc_ForceNewIteration);
  573. end
  574. else if LabelAccountedFor(tai_label(Next).labsym) then
  575. Continue;
  576. { If we reach here, we're at a label that hasn't been seen before
  577. (or JumpTracking was nil) }
  578. Break;
  579. end;
  580. until not Result or
  581. not (cs_opt_level3 in current_settings.optimizerswitches) or
  582. not (Next.typ in [ait_label, ait_instruction]) or
  583. RegInInstruction(reg,Next);
  584. end;
  585. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  586. begin
  587. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  588. begin
  589. Result:=GetNextInstruction(Current,Next);
  590. exit;
  591. end;
  592. Next:=tai(Current.Next);
  593. Result:=false;
  594. while assigned(Next) do
  595. begin
  596. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  597. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  598. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  599. exit
  600. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  601. begin
  602. Result:=true;
  603. exit;
  604. end;
  605. Next:=tai(Next.Next);
  606. end;
  607. end;
  608. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  609. begin
  610. Result:=RegReadByInstruction(reg,hp);
  611. end;
  612. class function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  613. var
  614. p: taicpu;
  615. opcount: longint;
  616. begin
  617. RegReadByInstruction := false;
  618. if hp.typ <> ait_instruction then
  619. exit;
  620. p := taicpu(hp);
  621. case p.opcode of
  622. A_CALL:
  623. regreadbyinstruction := true;
  624. A_IMUL:
  625. case p.ops of
  626. 1:
  627. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  628. (
  629. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  630. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  631. );
  632. 2,3:
  633. regReadByInstruction :=
  634. reginop(reg,p.oper[0]^) or
  635. reginop(reg,p.oper[1]^);
  636. else
  637. InternalError(2019112801);
  638. end;
  639. A_MUL:
  640. begin
  641. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  642. (
  643. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  644. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  645. );
  646. end;
  647. A_IDIV,A_DIV:
  648. begin
  649. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  650. (
  651. (getregtype(reg)=R_INTREGISTER) and
  652. (
  653. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  654. )
  655. );
  656. end;
  657. else
  658. begin
  659. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  660. begin
  661. RegReadByInstruction := false;
  662. exit;
  663. end;
  664. for opcount := 0 to p.ops-1 do
  665. if (p.oper[opCount]^.typ = top_ref) and
  666. RegInRef(reg,p.oper[opcount]^.ref^) then
  667. begin
  668. RegReadByInstruction := true;
  669. exit
  670. end;
  671. { special handling for SSE MOVSD }
  672. if (p.opcode=A_MOVSD) and (p.ops>0) then
  673. begin
  674. if p.ops<>2 then
  675. internalerror(2017042702);
  676. regReadByInstruction := reginop(reg,p.oper[0]^) or
  677. (
  678. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  679. );
  680. exit;
  681. end;
  682. with insprop[p.opcode] do
  683. begin
  684. case getregtype(reg) of
  685. R_INTREGISTER:
  686. begin
  687. case getsupreg(reg) of
  688. RS_EAX:
  689. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  690. begin
  691. RegReadByInstruction := true;
  692. exit
  693. end;
  694. RS_ECX:
  695. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  696. begin
  697. RegReadByInstruction := true;
  698. exit
  699. end;
  700. RS_EDX:
  701. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  702. begin
  703. RegReadByInstruction := true;
  704. exit
  705. end;
  706. RS_EBX:
  707. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  708. begin
  709. RegReadByInstruction := true;
  710. exit
  711. end;
  712. RS_ESP:
  713. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  714. begin
  715. RegReadByInstruction := true;
  716. exit
  717. end;
  718. RS_EBP:
  719. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  720. begin
  721. RegReadByInstruction := true;
  722. exit
  723. end;
  724. RS_ESI:
  725. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  726. begin
  727. RegReadByInstruction := true;
  728. exit
  729. end;
  730. RS_EDI:
  731. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  732. begin
  733. RegReadByInstruction := true;
  734. exit
  735. end;
  736. end;
  737. end;
  738. R_MMREGISTER:
  739. begin
  740. case getsupreg(reg) of
  741. RS_XMM0:
  742. if [Ch_RXMM0,Ch_RWXMM0,Ch_MXMM0]*Ch<>[] then
  743. begin
  744. RegReadByInstruction := true;
  745. exit
  746. end;
  747. end;
  748. end;
  749. else
  750. ;
  751. end;
  752. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  753. begin
  754. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  755. begin
  756. case p.condition of
  757. C_A,C_NBE, { CF=0 and ZF=0 }
  758. C_BE,C_NA: { CF=1 or ZF=1 }
  759. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  760. C_AE,C_NB,C_NC, { CF=0 }
  761. C_B,C_NAE,C_C: { CF=1 }
  762. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  763. C_NE,C_NZ, { ZF=0 }
  764. C_E,C_Z: { ZF=1 }
  765. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  766. C_G,C_NLE, { ZF=0 and SF=OF }
  767. C_LE,C_NG: { ZF=1 or SF<>OF }
  768. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  769. C_GE,C_NL, { SF=OF }
  770. C_L,C_NGE: { SF<>OF }
  771. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  772. C_NO, { OF=0 }
  773. C_O: { OF=1 }
  774. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  775. C_NP,C_PO, { PF=0 }
  776. C_P,C_PE: { PF=1 }
  777. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  778. C_NS, { SF=0 }
  779. C_S: { SF=1 }
  780. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  781. else
  782. internalerror(2017042701);
  783. end;
  784. if RegReadByInstruction then
  785. exit;
  786. end;
  787. case getsubreg(reg) of
  788. R_SUBW,R_SUBD,R_SUBQ:
  789. RegReadByInstruction :=
  790. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  791. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  792. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  793. R_SUBFLAGCARRY:
  794. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  795. R_SUBFLAGPARITY:
  796. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  797. R_SUBFLAGAUXILIARY:
  798. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  799. R_SUBFLAGZERO:
  800. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  801. R_SUBFLAGSIGN:
  802. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  803. R_SUBFLAGOVERFLOW:
  804. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  805. R_SUBFLAGINTERRUPT:
  806. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  807. R_SUBFLAGDIRECTION:
  808. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  809. else
  810. internalerror(2017042601);
  811. end;
  812. exit;
  813. end;
  814. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  815. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  816. (p.oper[0]^.reg=p.oper[1]^.reg) then
  817. exit;
  818. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  819. begin
  820. RegReadByInstruction := true;
  821. exit
  822. end;
  823. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  824. begin
  825. RegReadByInstruction := true;
  826. exit
  827. end;
  828. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  829. begin
  830. RegReadByInstruction := true;
  831. exit
  832. end;
  833. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  834. begin
  835. RegReadByInstruction := true;
  836. exit
  837. end;
  838. end;
  839. end;
  840. end;
  841. end;
  842. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  843. begin
  844. result:=false;
  845. if p1.typ<>ait_instruction then
  846. exit;
  847. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  848. exit(true);
  849. if (getregtype(reg)=R_INTREGISTER) and
  850. { change information for xmm movsd are not correct }
  851. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  852. begin
  853. case getsupreg(reg) of
  854. { RS_EAX = RS_RAX on x86-64 }
  855. RS_EAX:
  856. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  857. RS_ECX:
  858. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  859. RS_EDX:
  860. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  861. RS_EBX:
  862. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  863. RS_ESP:
  864. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  865. RS_EBP:
  866. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  867. RS_ESI:
  868. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  869. RS_EDI:
  870. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  871. else
  872. ;
  873. end;
  874. if result then
  875. exit;
  876. end
  877. else if getregtype(reg)=R_MMREGISTER then
  878. begin
  879. case getsupreg(reg) of
  880. RS_XMM0:
  881. result:=([Ch_RXMM0,Ch_WXMM0,Ch_RWXMM0,Ch_MXMM0]*insprop[taicpu(p1).opcode].Ch)<>[];
  882. else
  883. ;
  884. end;
  885. if result then
  886. exit;
  887. end
  888. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  889. begin
  890. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  891. exit(true);
  892. case getsubreg(reg) of
  893. R_SUBFLAGCARRY:
  894. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  895. R_SUBFLAGPARITY:
  896. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  897. R_SUBFLAGAUXILIARY:
  898. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  899. R_SUBFLAGZERO:
  900. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  901. R_SUBFLAGSIGN:
  902. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  903. R_SUBFLAGOVERFLOW:
  904. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  905. R_SUBFLAGINTERRUPT:
  906. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  907. R_SUBFLAGDIRECTION:
  908. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  909. R_SUBW,R_SUBD,R_SUBQ:
  910. { Everything except the direction bits }
  911. Result:=
  912. ([Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  913. Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  914. Ch_W0CarryFlag,Ch_W0ParityFlag,Ch_W0AuxiliaryFlag,Ch_W0ZeroFlag,Ch_W0SignFlag,Ch_W0OverflowFlag,
  915. Ch_W1CarryFlag,Ch_W1ParityFlag,Ch_W1AuxiliaryFlag,Ch_W1ZeroFlag,Ch_W1SignFlag,Ch_W1OverflowFlag,
  916. Ch_WUCarryFlag,Ch_WUParityFlag,Ch_WUAuxiliaryFlag,Ch_WUZeroFlag,Ch_WUSignFlag,Ch_WUOverflowFlag,
  917. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag
  918. ]*insprop[taicpu(p1).opcode].Ch)<>[];
  919. else
  920. ;
  921. end;
  922. if result then
  923. exit;
  924. end
  925. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  926. exit(true);
  927. Result:=inherited RegInInstruction(Reg, p1);
  928. end;
  929. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  930. const
  931. WriteOps: array[0..3] of set of TInsChange =
  932. ([CH_RWOP1,CH_WOP1,CH_MOP1],
  933. [Ch_RWOP2,Ch_WOP2,Ch_MOP2],
  934. [Ch_RWOP3,Ch_WOP3,Ch_MOP3],
  935. [Ch_RWOP4,Ch_WOP4,Ch_MOP4]);
  936. var
  937. OperIdx: Integer;
  938. begin
  939. Result := False;
  940. if p1.typ <> ait_instruction then
  941. exit;
  942. with insprop[taicpu(p1).opcode] do
  943. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  944. begin
  945. case getsubreg(reg) of
  946. R_SUBW,R_SUBD,R_SUBQ:
  947. Result :=
  948. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  949. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  950. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  951. R_SUBFLAGCARRY:
  952. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  953. R_SUBFLAGPARITY:
  954. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  955. R_SUBFLAGAUXILIARY:
  956. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  957. R_SUBFLAGZERO:
  958. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  959. R_SUBFLAGSIGN:
  960. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  961. R_SUBFLAGOVERFLOW:
  962. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  963. R_SUBFLAGINTERRUPT:
  964. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  965. R_SUBFLAGDIRECTION:
  966. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  967. else
  968. internalerror(2017042602);
  969. end;
  970. exit;
  971. end;
  972. case taicpu(p1).opcode of
  973. A_CALL:
  974. { We could potentially set Result to False if the register in
  975. question is non-volatile for the subroutine's calling convention,
  976. but this would require detecting the calling convention in use and
  977. also assuming that the routine doesn't contain malformed assembly
  978. language, for example... so it could only be done under -O4 as it
  979. would be considered a side-effect. [Kit] }
  980. Result := True;
  981. A_MOVSD:
  982. { special handling for SSE MOVSD }
  983. if (taicpu(p1).ops>0) then
  984. begin
  985. if taicpu(p1).ops<>2 then
  986. internalerror(2017042703);
  987. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  988. end;
  989. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  990. so fix it here (FK)
  991. }
  992. A_VMOVSS,
  993. A_VMOVSD:
  994. begin
  995. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  996. exit;
  997. end;
  998. A_IMUL:
  999. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  1000. else
  1001. ;
  1002. end;
  1003. if Result then
  1004. exit;
  1005. with insprop[taicpu(p1).opcode] do
  1006. begin
  1007. if getregtype(reg)=R_INTREGISTER then
  1008. begin
  1009. case getsupreg(reg) of
  1010. RS_EAX:
  1011. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX,Ch_WRAX,Ch_RWRAX,Ch_MRAX]*Ch<>[] then
  1012. begin
  1013. Result := True;
  1014. exit
  1015. end;
  1016. RS_ECX:
  1017. if [Ch_WECX,Ch_RWECX,Ch_MECX,Ch_WRCX,Ch_RWRCX,Ch_MRCX]*Ch<>[] then
  1018. begin
  1019. Result := True;
  1020. exit
  1021. end;
  1022. RS_EDX:
  1023. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX,Ch_WRDX,Ch_RWRDX,Ch_MRDX]*Ch<>[] then
  1024. begin
  1025. Result := True;
  1026. exit
  1027. end;
  1028. RS_EBX:
  1029. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX,Ch_WRBX,Ch_RWRBX,Ch_MRBX]*Ch<>[] then
  1030. begin
  1031. Result := True;
  1032. exit
  1033. end;
  1034. RS_ESP:
  1035. if [Ch_WESP,Ch_RWESP,Ch_MESP,Ch_WRSP,Ch_RWRSP,Ch_MRSP]*Ch<>[] then
  1036. begin
  1037. Result := True;
  1038. exit
  1039. end;
  1040. RS_EBP:
  1041. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP,Ch_WRBP,Ch_RWRBP,Ch_MRBP]*Ch<>[] then
  1042. begin
  1043. Result := True;
  1044. exit
  1045. end;
  1046. RS_ESI:
  1047. if [Ch_WESI,Ch_RWESI,Ch_MESI,Ch_WRSI,Ch_RWRSI,Ch_MRSI]*Ch<>[] then
  1048. begin
  1049. Result := True;
  1050. exit
  1051. end;
  1052. RS_EDI:
  1053. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI,Ch_WRDI,Ch_RWRDI,Ch_MRDI]*Ch<>[] then
  1054. begin
  1055. Result := True;
  1056. exit
  1057. end;
  1058. end;
  1059. end;
  1060. for OperIdx := 0 to taicpu(p1).ops - 1 do
  1061. if (WriteOps[OperIdx]*Ch<>[]) and
  1062. { The register doesn't get modified inside a reference }
  1063. (taicpu(p1).oper[OperIdx]^.typ = top_reg) and
  1064. SuperRegistersEqual(reg,taicpu(p1).oper[OperIdx]^.reg) then
  1065. begin
  1066. Result := true;
  1067. exit
  1068. end;
  1069. end;
  1070. end;
  1071. {$ifdef DEBUG_AOPTCPU}
  1072. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  1073. begin
  1074. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  1075. end;
  1076. function debug_tostr(i: tcgint): string; inline;
  1077. begin
  1078. Result := tostr(i);
  1079. end;
  1080. function debug_regname(r: TRegister): string; inline;
  1081. begin
  1082. Result := '%' + std_regname(r);
  1083. end;
  1084. { Debug output function - creates a string representation of an operator }
  1085. function debug_operstr(oper: TOper): string;
  1086. begin
  1087. case oper.typ of
  1088. top_const:
  1089. Result := '$' + debug_tostr(oper.val);
  1090. top_reg:
  1091. Result := debug_regname(oper.reg);
  1092. top_ref:
  1093. begin
  1094. if oper.ref^.offset <> 0 then
  1095. Result := debug_tostr(oper.ref^.offset) + '('
  1096. else
  1097. Result := '(';
  1098. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  1099. begin
  1100. Result := Result + debug_regname(oper.ref^.base);
  1101. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1102. Result := Result + ',' + debug_regname(oper.ref^.index);
  1103. end
  1104. else
  1105. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  1106. Result := Result + debug_regname(oper.ref^.index);
  1107. if (oper.ref^.scalefactor > 1) then
  1108. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  1109. else
  1110. Result := Result + ')';
  1111. end;
  1112. else
  1113. Result := '[UNKNOWN]';
  1114. end;
  1115. end;
  1116. function debug_op2str(opcode: tasmop): string; inline;
  1117. begin
  1118. Result := std_op2str[opcode];
  1119. end;
  1120. function debug_opsize2str(opsize: topsize): string; inline;
  1121. begin
  1122. Result := gas_opsize2str[opsize];
  1123. end;
  1124. {$else DEBUG_AOPTCPU}
  1125. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  1126. begin
  1127. end;
  1128. function debug_tostr(i: tcgint): string; inline;
  1129. begin
  1130. Result := '';
  1131. end;
  1132. function debug_regname(r: TRegister): string; inline;
  1133. begin
  1134. Result := '';
  1135. end;
  1136. function debug_operstr(oper: TOper): string; inline;
  1137. begin
  1138. Result := '';
  1139. end;
  1140. function debug_op2str(opcode: tasmop): string; inline;
  1141. begin
  1142. Result := '';
  1143. end;
  1144. function debug_opsize2str(opsize: topsize): string; inline;
  1145. begin
  1146. Result := '';
  1147. end;
  1148. {$endif DEBUG_AOPTCPU}
  1149. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  1150. begin
  1151. {$ifdef x86_64}
  1152. { Always fine on x86-64 }
  1153. Result := True;
  1154. {$else x86_64}
  1155. Result :=
  1156. {$ifdef i8086}
  1157. (current_settings.cputype >= cpu_386) and
  1158. {$endif i8086}
  1159. (
  1160. { Always accept if optimising for size }
  1161. (cs_opt_size in current_settings.optimizerswitches) or
  1162. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  1163. (current_settings.optimizecputype >= cpu_Pentium2)
  1164. );
  1165. {$endif x86_64}
  1166. end;
  1167. { Attempts to allocate a volatile integer register for use between p and hp,
  1168. using AUsedRegs for the current register usage information. Returns NR_NO
  1169. if no free register could be found }
  1170. function TX86AsmOptimizer.GetIntRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1171. var
  1172. RegSet: TCPURegisterSet;
  1173. CurrentSuperReg: Integer;
  1174. CurrentReg: TRegister;
  1175. Currentp: tai;
  1176. Breakout: Boolean;
  1177. begin
  1178. Result := NR_NO;
  1179. RegSet :=
  1180. paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption) +
  1181. current_procinfo.saved_regs_int;
  1182. for CurrentSuperReg in RegSet do
  1183. begin
  1184. CurrentReg := newreg(R_INTREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1185. if not AUsedRegs[R_INTREGISTER].IsUsed(CurrentReg)
  1186. {$if defined(i386) or defined(i8086)}
  1187. { If the target size is 8-bit, make sure we can actually encode it }
  1188. and (
  1189. (RegSize >= R_SUBW) or { Not R_SUBL or R_SUBH }
  1190. (GetSupReg(CurrentReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX])
  1191. )
  1192. {$endif i386 or i8086}
  1193. then
  1194. begin
  1195. Currentp := p;
  1196. Breakout := False;
  1197. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1198. begin
  1199. case Currentp.typ of
  1200. ait_instruction:
  1201. begin
  1202. if RegInInstruction(CurrentReg, Currentp) then
  1203. begin
  1204. Breakout := True;
  1205. Break;
  1206. end;
  1207. { Cannot allocate across an unconditional jump }
  1208. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1209. Exit;
  1210. end;
  1211. ait_marker:
  1212. { Don't try anything more if a marker is hit }
  1213. Exit;
  1214. ait_regalloc:
  1215. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1216. begin
  1217. Breakout := True;
  1218. Break;
  1219. end;
  1220. else
  1221. ;
  1222. end;
  1223. end;
  1224. if Breakout then
  1225. { Try the next register }
  1226. Continue;
  1227. { We have a free register available }
  1228. Result := CurrentReg;
  1229. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1230. Exit;
  1231. end;
  1232. end;
  1233. end;
  1234. { Attempts to allocate a volatile MM register for use between p and hp,
  1235. using AUsedRegs for the current register usage information. Returns NR_NO
  1236. if no free register could be found }
  1237. function TX86AsmOptimizer.GetMMRegisterBetween(RegSize: TSubRegister; var AUsedRegs: TAllUsedRegs; p, hp: tai): TRegister;
  1238. var
  1239. RegSet: TCPURegisterSet;
  1240. CurrentSuperReg: Integer;
  1241. CurrentReg: TRegister;
  1242. Currentp: tai;
  1243. Breakout: Boolean;
  1244. begin
  1245. Result := NR_NO;
  1246. RegSet :=
  1247. paramanager.get_volatile_registers_mm(current_procinfo.procdef.proccalloption) +
  1248. current_procinfo.saved_regs_mm;
  1249. for CurrentSuperReg in RegSet do
  1250. begin
  1251. CurrentReg := newreg(R_MMREGISTER, TSuperRegister(CurrentSuperReg), RegSize);
  1252. if not AUsedRegs[R_MMREGISTER].IsUsed(CurrentReg) then
  1253. begin
  1254. Currentp := p;
  1255. Breakout := False;
  1256. while not Breakout and GetNextInstruction(Currentp, Currentp) and (Currentp <> hp) do
  1257. begin
  1258. case Currentp.typ of
  1259. ait_instruction:
  1260. begin
  1261. if RegInInstruction(CurrentReg, Currentp) then
  1262. begin
  1263. Breakout := True;
  1264. Break;
  1265. end;
  1266. { Cannot allocate across an unconditional jump }
  1267. if is_calljmpuncondret(taicpu(Currentp).opcode) then
  1268. Exit;
  1269. end;
  1270. ait_marker:
  1271. { Don't try anything more if a marker is hit }
  1272. Exit;
  1273. ait_regalloc:
  1274. if (tai_regalloc(Currentp).ratype <> ra_dealloc) and SuperRegistersEqual(CurrentReg, tai_regalloc(Currentp).reg) then
  1275. begin
  1276. Breakout := True;
  1277. Break;
  1278. end;
  1279. else
  1280. ;
  1281. end;
  1282. end;
  1283. if Breakout then
  1284. { Try the next register }
  1285. Continue;
  1286. { We have a free register available }
  1287. Result := CurrentReg;
  1288. AllocRegBetween(CurrentReg, p, hp, AUsedRegs);
  1289. Exit;
  1290. end;
  1291. end;
  1292. end;
  1293. class function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  1294. begin
  1295. if not SuperRegistersEqual(reg1,reg2) then
  1296. exit(false);
  1297. if getregtype(reg1)<>R_INTREGISTER then
  1298. exit(true); {because SuperRegisterEqual is true}
  1299. case getsubreg(reg1) of
  1300. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  1301. higher, it preserves the high bits, so the new value depends on
  1302. reg2's previous value. In other words, it is equivalent to doing:
  1303. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  1304. R_SUBL:
  1305. exit(getsubreg(reg2)=R_SUBL);
  1306. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  1307. higher, it actually does a:
  1308. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  1309. R_SUBH:
  1310. exit(getsubreg(reg2)=R_SUBH);
  1311. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  1312. bits of reg2:
  1313. reg2 := (reg2 and $ffff0000) or word(reg1); }
  1314. R_SUBW:
  1315. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  1316. { a write to R_SUBD always overwrites every other subregister,
  1317. because it clears the high 32 bits of R_SUBQ on x86_64 }
  1318. R_SUBD,
  1319. R_SUBQ:
  1320. exit(true);
  1321. else
  1322. internalerror(2017042801);
  1323. end;
  1324. end;
  1325. class function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  1326. begin
  1327. if not SuperRegistersEqual(reg1,reg2) then
  1328. exit(false);
  1329. if getregtype(reg1)<>R_INTREGISTER then
  1330. exit(true); {because SuperRegisterEqual is true}
  1331. case getsubreg(reg1) of
  1332. R_SUBL:
  1333. exit(getsubreg(reg2)<>R_SUBH);
  1334. R_SUBH:
  1335. exit(getsubreg(reg2)<>R_SUBL);
  1336. R_SUBW,
  1337. R_SUBD,
  1338. R_SUBQ:
  1339. exit(true);
  1340. else
  1341. internalerror(2017042802);
  1342. end;
  1343. end;
  1344. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  1345. var
  1346. hp1 : tai;
  1347. l : TCGInt;
  1348. begin
  1349. result:=false;
  1350. { changes the code sequence
  1351. shr/sar const1, x
  1352. shl const2, x
  1353. to
  1354. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  1355. if GetNextInstruction(p, hp1) and
  1356. MatchInstruction(hp1,A_SHL,[]) and
  1357. (taicpu(p).oper[0]^.typ = top_const) and
  1358. (taicpu(hp1).oper[0]^.typ = top_const) and
  1359. (taicpu(hp1).opsize = taicpu(p).opsize) and
  1360. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  1361. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  1362. begin
  1363. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  1364. not(cs_opt_size in current_settings.optimizerswitches) then
  1365. begin
  1366. { shr/sar const1, %reg
  1367. shl const2, %reg
  1368. with const1 > const2 }
  1369. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  1370. taicpu(hp1).opcode := A_AND;
  1371. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  1372. case taicpu(p).opsize Of
  1373. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  1374. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  1375. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  1376. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1377. else
  1378. Internalerror(2017050703)
  1379. end;
  1380. end
  1381. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  1382. not(cs_opt_size in current_settings.optimizerswitches) then
  1383. begin
  1384. { shr/sar const1, %reg
  1385. shl const2, %reg
  1386. with const1 < const2 }
  1387. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  1388. taicpu(p).opcode := A_AND;
  1389. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1390. case taicpu(p).opsize Of
  1391. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1392. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1393. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1394. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1395. else
  1396. Internalerror(2017050702)
  1397. end;
  1398. end
  1399. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1400. begin
  1401. { shr/sar const1, %reg
  1402. shl const2, %reg
  1403. with const1 = const2 }
  1404. taicpu(p).opcode := A_AND;
  1405. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1406. case taicpu(p).opsize Of
  1407. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1408. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1409. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1410. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1411. else
  1412. Internalerror(2017050701)
  1413. end;
  1414. RemoveInstruction(hp1);
  1415. end;
  1416. end;
  1417. end;
  1418. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1419. var
  1420. opsize : topsize;
  1421. hp1, hp2 : tai;
  1422. tmpref : treference;
  1423. ShiftValue : Cardinal;
  1424. BaseValue : TCGInt;
  1425. begin
  1426. result:=false;
  1427. opsize:=taicpu(p).opsize;
  1428. { changes certain "imul const, %reg"'s to lea sequences }
  1429. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1430. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1431. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1432. if (taicpu(p).oper[0]^.val = 1) then
  1433. if (taicpu(p).ops = 2) then
  1434. { remove "imul $1, reg" }
  1435. begin
  1436. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1437. Result := RemoveCurrentP(p);
  1438. end
  1439. else
  1440. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1441. begin
  1442. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1443. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  1444. asml.InsertAfter(hp1, p);
  1445. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1446. RemoveCurrentP(p, hp1);
  1447. Result := True;
  1448. end
  1449. else if ((taicpu(p).ops <= 2) or
  1450. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1451. not(cs_opt_size in current_settings.optimizerswitches) and
  1452. (not(GetNextInstruction(p, hp1)) or
  1453. not((tai(hp1).typ = ait_instruction) and
  1454. ((taicpu(hp1).opcode=A_Jcc) and
  1455. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1456. begin
  1457. {
  1458. imul X, reg1, reg2 to
  1459. lea (reg1,reg1,Y), reg2
  1460. shl ZZ,reg2
  1461. imul XX, reg1 to
  1462. lea (reg1,reg1,YY), reg1
  1463. shl ZZ,reg2
  1464. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1465. it does not exist as a separate optimization target in FPC though.
  1466. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1467. at most two zeros
  1468. }
  1469. reference_reset(tmpref,1,[]);
  1470. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1471. begin
  1472. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1473. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1474. TmpRef.base := taicpu(p).oper[1]^.reg;
  1475. TmpRef.index := taicpu(p).oper[1]^.reg;
  1476. if not(BaseValue in [3,5,9]) then
  1477. Internalerror(2018110101);
  1478. TmpRef.ScaleFactor := BaseValue-1;
  1479. if (taicpu(p).ops = 2) then
  1480. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1481. else
  1482. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1483. AsmL.InsertAfter(hp1,p);
  1484. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1485. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1486. RemoveCurrentP(p, hp1);
  1487. if ShiftValue>0 then
  1488. begin
  1489. hp2 := taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg);
  1490. AsmL.InsertAfter(hp2,hp1);
  1491. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  1492. end;
  1493. Result := True;
  1494. end;
  1495. end;
  1496. end;
  1497. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1498. begin
  1499. Result := False;
  1500. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1501. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1502. begin
  1503. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1504. taicpu(p).opcode := A_MOV;
  1505. Result := True;
  1506. end;
  1507. end;
  1508. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1509. var
  1510. p: taicpu absolute hp; { Implicit typecast }
  1511. i: Integer;
  1512. begin
  1513. Result := False;
  1514. if not assigned(hp) or
  1515. (hp.typ <> ait_instruction) then
  1516. Exit;
  1517. Prefetch(insprop[p.opcode]);
  1518. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1519. with insprop[p.opcode] do
  1520. begin
  1521. case getsubreg(reg) of
  1522. R_SUBW,R_SUBD,R_SUBQ:
  1523. Result:=
  1524. { ZF, CF, OF, SF, PF and AF must all be set in some way (ordered so the most
  1525. uncommon flags are checked first }
  1526. ([Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags] * Ch <> []) and
  1527. ([Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch <> []) and
  1528. ([Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch <> []) and
  1529. ([Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch <> []) and
  1530. ([Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch <> []) and
  1531. ([Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch <> []);
  1532. R_SUBFLAGCARRY:
  1533. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1534. R_SUBFLAGPARITY:
  1535. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1536. R_SUBFLAGAUXILIARY:
  1537. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1538. R_SUBFLAGZERO:
  1539. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1540. R_SUBFLAGSIGN:
  1541. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1542. R_SUBFLAGOVERFLOW:
  1543. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1544. R_SUBFLAGINTERRUPT:
  1545. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1546. R_SUBFLAGDIRECTION:
  1547. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1548. else
  1549. internalerror(2017050501);
  1550. end;
  1551. exit;
  1552. end;
  1553. { Handle special cases first }
  1554. case p.opcode of
  1555. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1556. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1557. begin
  1558. Result :=
  1559. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1560. (p.oper[1]^.typ = top_reg) and
  1561. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1562. (
  1563. (p.oper[0]^.typ = top_const) or
  1564. (
  1565. (p.oper[0]^.typ = top_reg) and
  1566. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1567. ) or (
  1568. (p.oper[0]^.typ = top_ref) and
  1569. not RegInRef(reg,p.oper[0]^.ref^)
  1570. )
  1571. );
  1572. end;
  1573. A_MUL, A_IMUL:
  1574. Result :=
  1575. (
  1576. (p.ops=3) and { IMUL only }
  1577. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1578. (
  1579. (
  1580. (p.oper[1]^.typ=top_reg) and
  1581. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1582. ) or (
  1583. (p.oper[1]^.typ=top_ref) and
  1584. not RegInRef(reg,p.oper[1]^.ref^)
  1585. )
  1586. )
  1587. ) or (
  1588. (
  1589. (p.ops=1) and
  1590. (
  1591. (
  1592. (
  1593. (p.oper[0]^.typ=top_reg) and
  1594. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1595. )
  1596. ) or (
  1597. (p.oper[0]^.typ=top_ref) and
  1598. not RegInRef(reg,p.oper[0]^.ref^)
  1599. )
  1600. ) and (
  1601. (
  1602. (p.opsize=S_B) and
  1603. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1604. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1605. ) or (
  1606. (p.opsize=S_W) and
  1607. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1608. ) or (
  1609. (p.opsize=S_L) and
  1610. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1611. {$ifdef x86_64}
  1612. ) or (
  1613. (p.opsize=S_Q) and
  1614. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1615. {$endif x86_64}
  1616. )
  1617. )
  1618. )
  1619. );
  1620. A_CBW:
  1621. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1622. {$ifndef x86_64}
  1623. A_LDS:
  1624. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1625. A_LES:
  1626. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1627. {$endif not x86_64}
  1628. A_LFS:
  1629. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1630. A_LGS:
  1631. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1632. A_LSS:
  1633. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1634. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1635. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1636. A_LODSB:
  1637. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1638. A_LODSW:
  1639. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1640. {$ifdef x86_64}
  1641. A_LODSQ:
  1642. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1643. {$endif x86_64}
  1644. A_LODSD:
  1645. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1646. A_FSTSW, A_FNSTSW:
  1647. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1648. else
  1649. begin
  1650. with insprop[p.opcode] do
  1651. begin
  1652. if (
  1653. { xor %reg,%reg etc. is classed as a new value }
  1654. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1655. MatchOpType(p, top_reg, top_reg) and
  1656. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1657. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1658. ) then
  1659. begin
  1660. Result := True;
  1661. Exit;
  1662. end;
  1663. { Make sure the entire register is overwritten }
  1664. if (getregtype(reg) = R_INTREGISTER) then
  1665. begin
  1666. if (p.ops > 0) then
  1667. begin
  1668. if RegInOp(reg, p.oper[0]^) then
  1669. begin
  1670. if (p.oper[0]^.typ = top_ref) then
  1671. begin
  1672. if RegInRef(reg, p.oper[0]^.ref^) then
  1673. begin
  1674. Result := False;
  1675. Exit;
  1676. end;
  1677. end
  1678. else if (p.oper[0]^.typ = top_reg) then
  1679. begin
  1680. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1681. begin
  1682. Result := False;
  1683. Exit;
  1684. end
  1685. else if ([Ch_WOp1]*Ch<>[]) then
  1686. begin
  1687. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1688. Result := True
  1689. else
  1690. begin
  1691. Result := False;
  1692. Exit;
  1693. end;
  1694. end;
  1695. end;
  1696. end;
  1697. if (p.ops > 1) then
  1698. begin
  1699. if RegInOp(reg, p.oper[1]^) then
  1700. begin
  1701. if (p.oper[1]^.typ = top_ref) then
  1702. begin
  1703. if RegInRef(reg, p.oper[1]^.ref^) then
  1704. begin
  1705. Result := False;
  1706. Exit;
  1707. end;
  1708. end
  1709. else if (p.oper[1]^.typ = top_reg) then
  1710. begin
  1711. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1712. begin
  1713. Result := False;
  1714. Exit;
  1715. end
  1716. else if ([Ch_WOp2]*Ch<>[]) then
  1717. begin
  1718. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1719. Result := True
  1720. else
  1721. begin
  1722. Result := False;
  1723. Exit;
  1724. end;
  1725. end;
  1726. end;
  1727. end;
  1728. if (p.ops > 2) then
  1729. begin
  1730. if RegInOp(reg, p.oper[2]^) then
  1731. begin
  1732. if (p.oper[2]^.typ = top_ref) then
  1733. begin
  1734. if RegInRef(reg, p.oper[2]^.ref^) then
  1735. begin
  1736. Result := False;
  1737. Exit;
  1738. end;
  1739. end
  1740. else if (p.oper[2]^.typ = top_reg) then
  1741. begin
  1742. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1743. begin
  1744. Result := False;
  1745. Exit;
  1746. end
  1747. else if ([Ch_WOp3]*Ch<>[]) then
  1748. begin
  1749. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1750. Result := True
  1751. else
  1752. begin
  1753. Result := False;
  1754. Exit;
  1755. end;
  1756. end;
  1757. end;
  1758. end;
  1759. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1760. begin
  1761. if (p.oper[3]^.typ = top_ref) then
  1762. begin
  1763. if RegInRef(reg, p.oper[3]^.ref^) then
  1764. begin
  1765. Result := False;
  1766. Exit;
  1767. end;
  1768. end
  1769. else if (p.oper[3]^.typ = top_reg) then
  1770. begin
  1771. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1772. begin
  1773. Result := False;
  1774. Exit;
  1775. end
  1776. else if ([Ch_WOp4]*Ch<>[]) then
  1777. begin
  1778. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1779. Result := True
  1780. else
  1781. begin
  1782. Result := False;
  1783. Exit;
  1784. end;
  1785. end;
  1786. end;
  1787. end;
  1788. end;
  1789. end;
  1790. end;
  1791. { Don't do these ones first in case an input operand is equal to an explicit output register }
  1792. case getsupreg(reg) of
  1793. RS_EAX:
  1794. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1795. begin
  1796. Result := True;
  1797. Exit;
  1798. end;
  1799. RS_ECX:
  1800. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1801. begin
  1802. Result := True;
  1803. Exit;
  1804. end;
  1805. RS_EDX:
  1806. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1807. begin
  1808. Result := True;
  1809. Exit;
  1810. end;
  1811. RS_EBX:
  1812. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1813. begin
  1814. Result := True;
  1815. Exit;
  1816. end;
  1817. RS_ESP:
  1818. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1819. begin
  1820. Result := True;
  1821. Exit;
  1822. end;
  1823. RS_EBP:
  1824. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1825. begin
  1826. Result := True;
  1827. Exit;
  1828. end;
  1829. RS_ESI:
  1830. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1831. begin
  1832. Result := True;
  1833. Exit;
  1834. end;
  1835. RS_EDI:
  1836. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1837. begin
  1838. Result := True;
  1839. Exit;
  1840. end;
  1841. else
  1842. ;
  1843. end;
  1844. end;
  1845. end;
  1846. end;
  1847. end;
  1848. end;
  1849. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1850. var
  1851. hp2,hp3 : tai;
  1852. begin
  1853. { some x86-64 issue a NOP before the real exit code }
  1854. if MatchInstruction(p,A_NOP,[]) then
  1855. GetNextInstruction(p,p);
  1856. result:=assigned(p) and (p.typ=ait_instruction) and
  1857. ((taicpu(p).opcode = A_RET) or
  1858. ((taicpu(p).opcode=A_LEAVE) and
  1859. GetNextInstruction(p,hp2) and
  1860. MatchInstruction(hp2,A_RET,[S_NO])
  1861. ) or
  1862. (((taicpu(p).opcode=A_LEA) and
  1863. MatchOpType(taicpu(p),top_ref,top_reg) and
  1864. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1865. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1866. ) and
  1867. GetNextInstruction(p,hp2) and
  1868. MatchInstruction(hp2,A_RET,[S_NO])
  1869. ) or
  1870. ((((taicpu(p).opcode=A_MOV) and
  1871. MatchOpType(taicpu(p),top_reg,top_reg) and
  1872. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1873. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1874. ((taicpu(p).opcode=A_LEA) and
  1875. MatchOpType(taicpu(p),top_ref,top_reg) and
  1876. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1877. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1878. )
  1879. ) and
  1880. GetNextInstruction(p,hp2) and
  1881. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1882. MatchOpType(taicpu(hp2),top_reg) and
  1883. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1884. GetNextInstruction(hp2,hp3) and
  1885. MatchInstruction(hp3,A_RET,[S_NO])
  1886. )
  1887. );
  1888. end;
  1889. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1890. begin
  1891. isFoldableArithOp := False;
  1892. case hp1.opcode of
  1893. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1894. isFoldableArithOp :=
  1895. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1896. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1897. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1898. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1899. (taicpu(hp1).oper[1]^.reg = reg);
  1900. A_INC,A_DEC,A_NEG,A_NOT:
  1901. isFoldableArithOp :=
  1902. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1903. (taicpu(hp1).oper[0]^.reg = reg);
  1904. else
  1905. ;
  1906. end;
  1907. end;
  1908. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1909. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1910. var
  1911. hp2: tai;
  1912. begin
  1913. hp2 := p;
  1914. repeat
  1915. hp2 := tai(hp2.previous);
  1916. if assigned(hp2) and
  1917. (hp2.typ = ait_regalloc) and
  1918. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1919. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1920. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1921. begin
  1922. RemoveInstruction(hp2);
  1923. break;
  1924. end;
  1925. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1926. end;
  1927. begin
  1928. case current_procinfo.procdef.returndef.typ of
  1929. arraydef,recorddef,pointerdef,
  1930. stringdef,enumdef,procdef,objectdef,errordef,
  1931. filedef,setdef,procvardef,
  1932. classrefdef,forwarddef:
  1933. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1934. orddef:
  1935. if current_procinfo.procdef.returndef.size <> 0 then
  1936. begin
  1937. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1938. { for int64/qword }
  1939. if current_procinfo.procdef.returndef.size = 8 then
  1940. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1941. end;
  1942. else
  1943. ;
  1944. end;
  1945. end;
  1946. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1947. var
  1948. hp1,hp2 : tai;
  1949. begin
  1950. result:=false;
  1951. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1952. begin
  1953. { vmova* reg1,reg1
  1954. =>
  1955. <nop> }
  1956. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1957. begin
  1958. RemoveCurrentP(p);
  1959. result:=true;
  1960. exit;
  1961. end
  1962. else if GetNextInstruction(p,hp1) then
  1963. begin
  1964. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1965. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1966. begin
  1967. { vmova* reg1,reg2
  1968. vmova* reg2,reg3
  1969. dealloc reg2
  1970. =>
  1971. vmova* reg1,reg3 }
  1972. TransferUsedRegs(TmpUsedRegs);
  1973. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1974. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1975. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1976. begin
  1977. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1978. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1979. RemoveInstruction(hp1);
  1980. result:=true;
  1981. exit;
  1982. end
  1983. { special case:
  1984. vmova* reg1,<op>
  1985. vmova* <op>,reg1
  1986. =>
  1987. vmova* reg1,<op> }
  1988. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1989. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1990. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1991. ) then
  1992. begin
  1993. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1994. RemoveInstruction(hp1);
  1995. result:=true;
  1996. exit;
  1997. end
  1998. end
  1999. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  2000. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  2001. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  2002. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  2003. ) and
  2004. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2005. begin
  2006. { vmova* reg1,reg2
  2007. vmovs* reg2,<op>
  2008. dealloc reg2
  2009. =>
  2010. vmovs* reg1,reg3 }
  2011. TransferUsedRegs(TmpUsedRegs);
  2012. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2013. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2014. begin
  2015. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  2016. taicpu(p).opcode:=taicpu(hp1).opcode;
  2017. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  2018. RemoveInstruction(hp1);
  2019. result:=true;
  2020. exit;
  2021. end
  2022. end;
  2023. end;
  2024. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  2025. begin
  2026. if MatchInstruction(hp1,[A_VFMADDPD,
  2027. A_VFMADD132PD,
  2028. A_VFMADD132PS,
  2029. A_VFMADD132SD,
  2030. A_VFMADD132SS,
  2031. A_VFMADD213PD,
  2032. A_VFMADD213PS,
  2033. A_VFMADD213SD,
  2034. A_VFMADD213SS,
  2035. A_VFMADD231PD,
  2036. A_VFMADD231PS,
  2037. A_VFMADD231SD,
  2038. A_VFMADD231SS,
  2039. A_VFMADDSUB132PD,
  2040. A_VFMADDSUB132PS,
  2041. A_VFMADDSUB213PD,
  2042. A_VFMADDSUB213PS,
  2043. A_VFMADDSUB231PD,
  2044. A_VFMADDSUB231PS,
  2045. A_VFMSUB132PD,
  2046. A_VFMSUB132PS,
  2047. A_VFMSUB132SD,
  2048. A_VFMSUB132SS,
  2049. A_VFMSUB213PD,
  2050. A_VFMSUB213PS,
  2051. A_VFMSUB213SD,
  2052. A_VFMSUB213SS,
  2053. A_VFMSUB231PD,
  2054. A_VFMSUB231PS,
  2055. A_VFMSUB231SD,
  2056. A_VFMSUB231SS,
  2057. A_VFMSUBADD132PD,
  2058. A_VFMSUBADD132PS,
  2059. A_VFMSUBADD213PD,
  2060. A_VFMSUBADD213PS,
  2061. A_VFMSUBADD231PD,
  2062. A_VFMSUBADD231PS,
  2063. A_VFNMADD132PD,
  2064. A_VFNMADD132PS,
  2065. A_VFNMADD132SD,
  2066. A_VFNMADD132SS,
  2067. A_VFNMADD213PD,
  2068. A_VFNMADD213PS,
  2069. A_VFNMADD213SD,
  2070. A_VFNMADD213SS,
  2071. A_VFNMADD231PD,
  2072. A_VFNMADD231PS,
  2073. A_VFNMADD231SD,
  2074. A_VFNMADD231SS,
  2075. A_VFNMSUB132PD,
  2076. A_VFNMSUB132PS,
  2077. A_VFNMSUB132SD,
  2078. A_VFNMSUB132SS,
  2079. A_VFNMSUB213PD,
  2080. A_VFNMSUB213PS,
  2081. A_VFNMSUB213SD,
  2082. A_VFNMSUB213SS,
  2083. A_VFNMSUB231PD,
  2084. A_VFNMSUB231PS,
  2085. A_VFNMSUB231SD,
  2086. A_VFNMSUB231SS],[S_NO]) and
  2087. { we mix single and double opperations here because we assume that the compiler
  2088. generates vmovapd only after double operations and vmovaps only after single operations }
  2089. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  2090. GetNextInstruction(hp1,hp2) and
  2091. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  2092. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  2093. begin
  2094. TransferUsedRegs(TmpUsedRegs);
  2095. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2096. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2097. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2098. begin
  2099. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  2100. RemoveCurrentP(p);
  2101. RemoveInstruction(hp2);
  2102. end;
  2103. end
  2104. else if (hp1.typ = ait_instruction) and
  2105. GetNextInstruction(hp1, hp2) and
  2106. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  2107. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  2108. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2109. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  2110. (((taicpu(p).opcode=A_MOVAPS) and
  2111. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  2112. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  2113. ((taicpu(p).opcode=A_MOVAPD) and
  2114. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  2115. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  2116. ) then
  2117. { change
  2118. movapX reg,reg2
  2119. addsX/subsX/... reg3, reg2
  2120. movapX reg2,reg
  2121. to
  2122. addsX/subsX/... reg3,reg
  2123. }
  2124. begin
  2125. TransferUsedRegs(TmpUsedRegs);
  2126. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2127. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2128. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  2129. begin
  2130. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  2131. debug_op2str(taicpu(p).opcode)+' '+
  2132. debug_op2str(taicpu(hp1).opcode)+' '+
  2133. debug_op2str(taicpu(hp2).opcode)+') done',p);
  2134. { we cannot eliminate the first move if
  2135. the operations uses the same register for source and dest }
  2136. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2137. { Remember that hp1 is not necessarily the immediate
  2138. next instruction }
  2139. RemoveCurrentP(p);
  2140. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  2141. RemoveInstruction(hp2);
  2142. result:=true;
  2143. end;
  2144. end
  2145. else if (hp1.typ = ait_instruction) and
  2146. (((taicpu(p).opcode=A_VMOVAPD) and
  2147. (taicpu(hp1).opcode=A_VCOMISD)) or
  2148. ((taicpu(p).opcode=A_VMOVAPS) and
  2149. ((taicpu(hp1).opcode=A_VCOMISS))
  2150. )
  2151. ) and not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  2152. { change
  2153. movapX reg,reg1
  2154. vcomisX reg1,reg1
  2155. to
  2156. vcomisX reg,reg
  2157. }
  2158. begin
  2159. TransferUsedRegs(TmpUsedRegs);
  2160. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2161. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  2162. begin
  2163. DebugMsg(SPeepholeOptimization + 'MovapXComisX2ComisX2 ('+
  2164. debug_op2str(taicpu(p).opcode)+' '+
  2165. debug_op2str(taicpu(hp1).opcode)+') done',p);
  2166. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2167. taicpu(hp1).loadoper(0, taicpu(p).oper[0]^);
  2168. if OpsEqual(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2169. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  2170. RemoveCurrentP(p);
  2171. result:=true;
  2172. exit;
  2173. end;
  2174. end
  2175. end;
  2176. end;
  2177. end;
  2178. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  2179. var
  2180. hp1 : tai;
  2181. begin
  2182. result:=false;
  2183. { replace
  2184. V<Op>X %mreg1,%mreg2,%mreg3
  2185. VMovX %mreg3,%mreg4
  2186. dealloc %mreg3
  2187. by
  2188. V<Op>X %mreg1,%mreg2,%mreg4
  2189. ?
  2190. }
  2191. if GetNextInstruction(p,hp1) and
  2192. { we mix single and double operations here because we assume that the compiler
  2193. generates vmovapd only after double operations and vmovaps only after single operations }
  2194. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  2195. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  2196. (taicpu(hp1).oper[1]^.typ=top_reg) then
  2197. begin
  2198. TransferUsedRegs(TmpUsedRegs);
  2199. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  2200. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  2201. begin
  2202. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  2203. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  2204. RemoveInstruction(hp1);
  2205. result:=true;
  2206. end;
  2207. end;
  2208. end;
  2209. { Replaces all references to AOldReg in a memory reference to ANewReg }
  2210. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  2211. begin
  2212. Result := False;
  2213. { For safety reasons, only check for exact register matches }
  2214. { Check base register }
  2215. if (ref.base = AOldReg) then
  2216. begin
  2217. ref.base := ANewReg;
  2218. Result := True;
  2219. end;
  2220. { Check index register }
  2221. if (ref.index = AOldReg) then
  2222. begin
  2223. ref.index := ANewReg;
  2224. Result := True;
  2225. end;
  2226. end;
  2227. { Replaces all references to AOldReg in an operand to ANewReg }
  2228. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  2229. var
  2230. OldSupReg, NewSupReg: TSuperRegister;
  2231. OldSubReg, NewSubReg: TSubRegister;
  2232. OldRegType: TRegisterType;
  2233. ThisOper: POper;
  2234. begin
  2235. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  2236. Result := False;
  2237. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  2238. InternalError(2020011801);
  2239. OldSupReg := getsupreg(AOldReg);
  2240. OldSubReg := getsubreg(AOldReg);
  2241. OldRegType := getregtype(AOldReg);
  2242. NewSupReg := getsupreg(ANewReg);
  2243. NewSubReg := getsubreg(ANewReg);
  2244. if OldRegType <> getregtype(ANewReg) then
  2245. InternalError(2020011802);
  2246. if OldSubReg <> NewSubReg then
  2247. InternalError(2020011803);
  2248. case ThisOper^.typ of
  2249. top_reg:
  2250. if (
  2251. (ThisOper^.reg = AOldReg) or
  2252. (
  2253. (OldRegType = R_INTREGISTER) and
  2254. (getsupreg(ThisOper^.reg) = OldSupReg) and
  2255. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  2256. (
  2257. (getsubreg(ThisOper^.reg) <= OldSubReg)
  2258. {$ifndef x86_64}
  2259. and (
  2260. { Under i386 and i8086, ESI, EDI, EBP and ESP
  2261. don't have an 8-bit representation }
  2262. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  2263. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  2264. )
  2265. {$endif x86_64}
  2266. )
  2267. )
  2268. ) then
  2269. begin
  2270. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  2271. Result := True;
  2272. end;
  2273. top_ref:
  2274. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  2275. Result := True;
  2276. else
  2277. ;
  2278. end;
  2279. end;
  2280. { Replaces all references to AOldReg in an instruction to ANewReg }
  2281. class function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  2282. const
  2283. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  2284. var
  2285. OperIdx: Integer;
  2286. begin
  2287. Result := False;
  2288. for OperIdx := 0 to p.ops - 1 do
  2289. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) then
  2290. begin
  2291. { The shift and rotate instructions can only use CL }
  2292. if not (
  2293. (OperIdx = 0) and
  2294. { This second condition just helps to avoid unnecessarily
  2295. calling MatchInstruction for 10 different opcodes }
  2296. (p.oper[0]^.reg = NR_CL) and
  2297. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  2298. ) then
  2299. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2300. end
  2301. else if p.oper[OperIdx]^.typ = top_ref then
  2302. { It's okay to replace registers in references that get written to }
  2303. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  2304. end;
  2305. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean;
  2306. begin
  2307. with ref^ do
  2308. Result :=
  2309. (index = NR_NO) and
  2310. (
  2311. {$ifdef x86_64}
  2312. (
  2313. (base = NR_RIP) and
  2314. (refaddr in [addr_pic, addr_pic_no_got])
  2315. ) or
  2316. {$endif x86_64}
  2317. (base = NR_STACK_POINTER_REG) or
  2318. (base = current_procinfo.framepointer)
  2319. );
  2320. end;
  2321. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  2322. var
  2323. l: asizeint;
  2324. begin
  2325. Result := False;
  2326. { Should have been checked previously }
  2327. if p.opcode <> A_LEA then
  2328. InternalError(2020072501);
  2329. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  2330. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  2331. not(cs_opt_size in current_settings.optimizerswitches) then
  2332. exit;
  2333. with p.oper[0]^.ref^ do
  2334. begin
  2335. if (base <> p.oper[1]^.reg) or
  2336. (index <> NR_NO) or
  2337. assigned(symbol) then
  2338. exit;
  2339. l:=offset;
  2340. if (l=1) and UseIncDec then
  2341. begin
  2342. p.opcode:=A_INC;
  2343. p.loadreg(0,p.oper[1]^.reg);
  2344. p.ops:=1;
  2345. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  2346. end
  2347. else if (l=-1) and UseIncDec then
  2348. begin
  2349. p.opcode:=A_DEC;
  2350. p.loadreg(0,p.oper[1]^.reg);
  2351. p.ops:=1;
  2352. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  2353. end
  2354. else
  2355. begin
  2356. if (l<0) and (l<>-2147483648) then
  2357. begin
  2358. p.opcode:=A_SUB;
  2359. p.loadConst(0,-l);
  2360. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  2361. end
  2362. else
  2363. begin
  2364. p.opcode:=A_ADD;
  2365. p.loadConst(0,l);
  2366. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  2367. end;
  2368. end;
  2369. end;
  2370. Result := True;
  2371. end;
  2372. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  2373. var
  2374. CurrentReg, ReplaceReg: TRegister;
  2375. begin
  2376. Result := False;
  2377. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  2378. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  2379. case hp.opcode of
  2380. A_FSTSW, A_FNSTSW,
  2381. A_IN, A_INS, A_OUT, A_OUTS,
  2382. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2383. { These routines have explicit operands, but they are restricted in
  2384. what they can be (e.g. IN and OUT can only read from AL, AX or
  2385. EAX. }
  2386. Exit;
  2387. A_IMUL:
  2388. begin
  2389. { The 1-operand version writes to implicit registers
  2390. The 2-operand version reads from the first operator, and reads
  2391. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  2392. the 3-operand version reads from a register that it doesn't write to
  2393. }
  2394. case hp.ops of
  2395. 1:
  2396. if (
  2397. (
  2398. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  2399. ) or
  2400. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  2401. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2402. begin
  2403. Result := True;
  2404. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  2405. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2406. end;
  2407. 2:
  2408. { Only modify the first parameter }
  2409. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  2410. begin
  2411. Result := True;
  2412. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  2413. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2414. end;
  2415. 3:
  2416. { Only modify the second parameter }
  2417. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  2418. begin
  2419. Result := True;
  2420. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  2421. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2422. end;
  2423. else
  2424. InternalError(2020012901);
  2425. end;
  2426. end;
  2427. else
  2428. if (hp.ops > 0) and
  2429. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  2430. begin
  2431. Result := True;
  2432. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  2433. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  2434. end;
  2435. end;
  2436. end;
  2437. function TX86AsmOptimizer.FuncMov2Func(var p: tai; const hp1: tai): Boolean;
  2438. var
  2439. hp2: tai;
  2440. p_SourceReg, p_TargetReg: TRegister;
  2441. begin
  2442. Result := False;
  2443. { Backward optimisation. If we have:
  2444. func. %reg1,%reg2
  2445. mov %reg2,%reg3
  2446. (dealloc %reg2)
  2447. Change to:
  2448. func. %reg1,%reg3 (see comment below for what a valid func. is)
  2449. Perform similar optimisations with 1, 3 and 4-operand instructions
  2450. that only have one output.
  2451. }
  2452. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2453. begin
  2454. p_SourceReg := taicpu(p).oper[0]^.reg;
  2455. p_TargetReg := taicpu(p).oper[1]^.reg;
  2456. TransferUsedRegs(TmpUsedRegs);
  2457. if not RegUsedAfterInstruction(p_SourceReg, p, TmpUsedRegs) and
  2458. GetLastInstruction(p, hp2) and
  2459. (hp2.typ = ait_instruction) and
  2460. { Have to make sure it's an instruction that only reads from
  2461. the first operands and only writes (not reads or modifies) to
  2462. the last one; in essence, a pure function such as BSR, POPCNT
  2463. or ANDN }
  2464. (
  2465. (
  2466. (taicpu(hp2).ops = 1) and
  2467. (insprop[taicpu(hp2).opcode].Ch * [Ch_Wop1] = [Ch_Wop1])
  2468. ) or
  2469. (
  2470. (taicpu(hp2).ops = 2) and
  2471. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Wop2] = [Ch_Rop1, Ch_Wop2])
  2472. ) or
  2473. (
  2474. (taicpu(hp2).ops = 3) and
  2475. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Wop3] = [Ch_Rop1, Ch_Rop2, Ch_Wop3])
  2476. ) or
  2477. (
  2478. (taicpu(hp2).ops = 4) and
  2479. (insprop[taicpu(hp2).opcode].Ch * [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4] = [Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Wop4])
  2480. )
  2481. ) and
  2482. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.typ = top_reg) and
  2483. (taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg = p_SourceReg) then
  2484. begin
  2485. case taicpu(hp2).opcode of
  2486. A_FSTSW, A_FNSTSW,
  2487. A_IN, A_INS, A_OUT, A_OUTS,
  2488. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  2489. { These routines have explicit operands, but they are restricted in
  2490. what they can be (e.g. IN and OUT can only read from AL, AX or
  2491. EAX. }
  2492. ;
  2493. else
  2494. begin
  2495. DebugMsg(SPeepholeOptimization + 'Removed MOV and changed destination on previous instruction to optimise register usage (FuncMov2Func)', p);
  2496. taicpu(hp2).oper[taicpu(hp2).ops-1]^.reg := p_TargetReg;
  2497. if not RegInInstruction(p_TargetReg, hp2) then
  2498. begin
  2499. { Since we're allocating from an earlier point, we
  2500. need to remove the register from the tracking }
  2501. ExcludeRegFromUsedRegs(p_TargetReg, TmpUsedRegs);
  2502. AllocRegBetween(p_TargetReg, hp2, p, TmpUsedRegs);
  2503. end;
  2504. RemoveCurrentp(p, hp1);
  2505. { If the Func was another MOV instruction, we might get
  2506. "mov %reg,%reg" that doesn't get removed in Pass 2
  2507. otherwise, so deal with it here (also do something
  2508. similar with lea (%reg),%reg}
  2509. if (taicpu(hp2).opcode = A_MOV) and MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp2).oper[1]^.reg) then
  2510. begin
  2511. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1a done', hp2);
  2512. if p = hp2 then
  2513. RemoveCurrentp(p)
  2514. else
  2515. RemoveInstruction(hp2);
  2516. end;
  2517. Result := True;
  2518. Exit;
  2519. end;
  2520. end;
  2521. end;
  2522. end;
  2523. end;
  2524. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2525. var
  2526. hp1, hp2, hp3: tai;
  2527. DoOptimisation, TempBool: Boolean;
  2528. {$ifdef x86_64}
  2529. NewConst: TCGInt;
  2530. {$endif x86_64}
  2531. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2532. begin
  2533. if taicpu(hp1).opcode = signed_movop then
  2534. begin
  2535. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2536. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2537. end
  2538. else
  2539. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2540. end;
  2541. function TryConstMerge(var p1, p2: tai): Boolean;
  2542. var
  2543. ThisRef: TReference;
  2544. begin
  2545. Result := False;
  2546. ThisRef := taicpu(p2).oper[1]^.ref^;
  2547. { Only permit writes to the stack, since we can guarantee alignment with that }
  2548. if (ThisRef.index = NR_NO) and
  2549. (
  2550. (ThisRef.base = NR_STACK_POINTER_REG) or
  2551. (ThisRef.base = current_procinfo.framepointer)
  2552. ) then
  2553. begin
  2554. case taicpu(p).opsize of
  2555. S_B:
  2556. begin
  2557. { Word writes must be on a 2-byte boundary }
  2558. if (taicpu(p1).oper[1]^.ref^.offset mod 2) = 0 then
  2559. begin
  2560. { Reduce offset of second reference to see if it is sequential with the first }
  2561. Dec(ThisRef.offset, 1);
  2562. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2563. begin
  2564. { Make sure the constants aren't represented as a
  2565. negative number, as these won't merge properly }
  2566. taicpu(p1).opsize := S_W;
  2567. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FF) or ((taicpu(p2).oper[0]^.val and $FF) shl 8);
  2568. DebugMsg(SPeepholeOptimization + 'Merged two byte-sized constant writes to stack (MovMov2Mov 2a)', p1);
  2569. RemoveInstruction(p2);
  2570. Result := True;
  2571. end;
  2572. end;
  2573. end;
  2574. S_W:
  2575. begin
  2576. { Longword writes must be on a 4-byte boundary }
  2577. if (taicpu(p1).oper[1]^.ref^.offset mod 4) = 0 then
  2578. begin
  2579. { Reduce offset of second reference to see if it is sequential with the first }
  2580. Dec(ThisRef.offset, 2);
  2581. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2582. begin
  2583. { Make sure the constants aren't represented as a
  2584. negative number, as these won't merge properly }
  2585. taicpu(p1).opsize := S_L;
  2586. taicpu(p1).oper[0]^.val := (taicpu(p1).oper[0]^.val and $FFFF) or ((taicpu(p2).oper[0]^.val and $FFFF) shl 16);
  2587. DebugMsg(SPeepholeOptimization + 'Merged two word-sized constant writes to stack (MovMov2Mov 2b)', p1);
  2588. RemoveInstruction(p2);
  2589. Result := True;
  2590. end;
  2591. end;
  2592. end;
  2593. {$ifdef x86_64}
  2594. S_L:
  2595. begin
  2596. { Only sign-extended 32-bit constants can be written to 64-bit memory directly, so check to
  2597. see if the constants can be encoded this way. }
  2598. NewConst := (taicpu(p1).oper[0]^.val and $FFFFFFFF) or (taicpu(p2).oper[0]^.val shl 32);
  2599. if (NewConst >= -2147483648) and (NewConst <= 2147483647) and
  2600. { Quadword writes must be on an 8-byte boundary }
  2601. ((taicpu(p1).oper[1]^.ref^.offset mod 8) = 0) then
  2602. begin
  2603. { Reduce offset of second reference to see if it is sequential with the first }
  2604. Dec(ThisRef.offset, 4);
  2605. if RefsEqual(taicpu(p1).oper[1]^.ref^, ThisRef) then
  2606. begin
  2607. { Make sure the constants aren't represented as a
  2608. negative number, as these won't merge properly }
  2609. taicpu(p1).opsize := S_Q;
  2610. { Force a typecast into a 32-bit signed integer (that will then be sign-extended to 64-bit) }
  2611. taicpu(p1).oper[0]^.val := NewConst;
  2612. DebugMsg(SPeepholeOptimization + 'Merged two longword-sized constant writes to stack (MovMov2Mov 2c)', p1);
  2613. RemoveInstruction(p2);
  2614. Result := True;
  2615. end;
  2616. end;
  2617. end;
  2618. {$endif x86_64}
  2619. else
  2620. ;
  2621. end;
  2622. end;
  2623. end;
  2624. var
  2625. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2626. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2627. NewSize: topsize; NewOffset: asizeint;
  2628. p_SourceReg, p_TargetReg, NewMMReg: TRegister;
  2629. SourceRef, TargetRef: TReference;
  2630. MovAligned, MovUnaligned: TAsmOp;
  2631. ThisRef: TReference;
  2632. JumpTracking: TLinkedList;
  2633. begin
  2634. Result:=false;
  2635. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2636. { remove mov reg1,reg1? }
  2637. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2638. then
  2639. begin
  2640. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2641. { take care of the register (de)allocs following p }
  2642. RemoveCurrentP(p, hp1);
  2643. Result:=true;
  2644. exit;
  2645. end;
  2646. { All the next optimisations require a next instruction }
  2647. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2648. Exit;
  2649. { Prevent compiler warnings }
  2650. p_TargetReg := NR_NO;
  2651. if taicpu(p).oper[1]^.typ = top_reg then
  2652. begin
  2653. { Saves on a large number of dereferences }
  2654. p_TargetReg := taicpu(p).oper[1]^.reg;
  2655. { Look for:
  2656. mov %reg1,%reg2
  2657. ??? %reg2,r/m
  2658. Change to:
  2659. mov %reg1,%reg2
  2660. ??? %reg1,r/m
  2661. }
  2662. if taicpu(p).oper[0]^.typ = top_reg then
  2663. begin
  2664. if RegReadByInstruction(p_TargetReg, hp1) and
  2665. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2666. begin
  2667. { A change has occurred, just not in p }
  2668. Result := True;
  2669. TransferUsedRegs(TmpUsedRegs);
  2670. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2671. if not RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs) and
  2672. { Just in case something didn't get modified (e.g. an
  2673. implicit register) }
  2674. not RegReadByInstruction(p_TargetReg, hp1) then
  2675. begin
  2676. { We can remove the original MOV }
  2677. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2678. RemoveCurrentp(p, hp1);
  2679. { UsedRegs got updated by RemoveCurrentp }
  2680. Result := True;
  2681. Exit;
  2682. end;
  2683. { If we know a MOV instruction has become a null operation, we might as well
  2684. get rid of it now to save time. }
  2685. if (taicpu(hp1).opcode = A_MOV) and
  2686. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2687. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2688. { Just being a register is enough to confirm it's a null operation }
  2689. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2690. begin
  2691. Result := True;
  2692. { Speed-up to reduce a pipeline stall... if we had something like...
  2693. movl %eax,%edx
  2694. movw %dx,%ax
  2695. ... the second instruction would change to movw %ax,%ax, but
  2696. given that it is now %ax that's active rather than %eax,
  2697. penalties might occur due to a partial register write, so instead,
  2698. change it to a MOVZX instruction when optimising for speed.
  2699. }
  2700. if not (cs_opt_size in current_settings.optimizerswitches) and
  2701. IsMOVZXAcceptable and
  2702. (taicpu(hp1).opsize < taicpu(p).opsize)
  2703. {$ifdef x86_64}
  2704. { operations already implicitly set the upper 64 bits to zero }
  2705. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2706. {$endif x86_64}
  2707. then
  2708. begin
  2709. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2710. case taicpu(p).opsize of
  2711. S_W:
  2712. if taicpu(hp1).opsize = S_B then
  2713. taicpu(hp1).opsize := S_BL
  2714. else
  2715. InternalError(2020012911);
  2716. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2717. case taicpu(hp1).opsize of
  2718. S_B:
  2719. taicpu(hp1).opsize := S_BL;
  2720. S_W:
  2721. taicpu(hp1).opsize := S_WL;
  2722. else
  2723. InternalError(2020012912);
  2724. end;
  2725. else
  2726. InternalError(2020012910);
  2727. end;
  2728. taicpu(hp1).opcode := A_MOVZX;
  2729. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2730. end
  2731. else
  2732. begin
  2733. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2734. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2735. RemoveInstruction(hp1);
  2736. { The instruction after what was hp1 is now the immediate next instruction,
  2737. so we can continue to make optimisations if it's present }
  2738. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2739. Exit;
  2740. hp1 := hp2;
  2741. end;
  2742. end;
  2743. end;
  2744. end;
  2745. end;
  2746. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2747. overwrites the original destination register. e.g.
  2748. movl ###,%reg2d
  2749. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2750. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2751. }
  2752. if (taicpu(p).oper[1]^.typ = top_reg) and
  2753. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2754. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2755. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2756. begin
  2757. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2758. begin
  2759. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2760. case taicpu(p).oper[0]^.typ of
  2761. top_const:
  2762. { We have something like:
  2763. movb $x, %regb
  2764. movzbl %regb,%regd
  2765. Change to:
  2766. movl $x, %regd
  2767. }
  2768. begin
  2769. case taicpu(hp1).opsize of
  2770. S_BW:
  2771. begin
  2772. convert_mov_value(A_MOVSX, $FF);
  2773. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2774. taicpu(p).opsize := S_W;
  2775. end;
  2776. S_BL:
  2777. begin
  2778. convert_mov_value(A_MOVSX, $FF);
  2779. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2780. taicpu(p).opsize := S_L;
  2781. end;
  2782. S_WL:
  2783. begin
  2784. convert_mov_value(A_MOVSX, $FFFF);
  2785. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2786. taicpu(p).opsize := S_L;
  2787. end;
  2788. {$ifdef x86_64}
  2789. S_BQ:
  2790. begin
  2791. convert_mov_value(A_MOVSX, $FF);
  2792. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2793. taicpu(p).opsize := S_Q;
  2794. end;
  2795. S_WQ:
  2796. begin
  2797. convert_mov_value(A_MOVSX, $FFFF);
  2798. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2799. taicpu(p).opsize := S_Q;
  2800. end;
  2801. S_LQ:
  2802. begin
  2803. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2804. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2805. taicpu(p).opsize := S_Q;
  2806. end;
  2807. {$endif x86_64}
  2808. else
  2809. { If hp1 was a MOV instruction, it should have been
  2810. optimised already }
  2811. InternalError(2020021001);
  2812. end;
  2813. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2814. RemoveInstruction(hp1);
  2815. Result := True;
  2816. Exit;
  2817. end;
  2818. top_ref:
  2819. begin
  2820. { We have something like:
  2821. movb mem, %regb
  2822. movzbl %regb,%regd
  2823. Change to:
  2824. movzbl mem, %regd
  2825. }
  2826. ThisRef := taicpu(p).oper[0]^.ref^;
  2827. if (ThisRef.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2828. begin
  2829. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2830. taicpu(hp1).loadref(0, ThisRef);
  2831. { Make sure any registers in the references are properly tracked }
  2832. if (ThisRef.base <> NR_NO){$ifdef x86_64} and (ThisRef.base <> NR_RIP){$endif x86_64} then
  2833. AllocRegBetween(ThisRef.base, p, hp1, UsedRegs);
  2834. if (ThisRef.index <> NR_NO) then
  2835. AllocRegBetween(ThisRef.index, p, hp1, UsedRegs);
  2836. RemoveCurrentP(p, hp1);
  2837. Result := True;
  2838. Exit;
  2839. end;
  2840. end;
  2841. else
  2842. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2843. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2844. Exit;
  2845. end;
  2846. end
  2847. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2848. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2849. optimised }
  2850. else
  2851. begin
  2852. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2853. RemoveCurrentP(p, hp1);
  2854. Result := True;
  2855. Exit;
  2856. end;
  2857. end;
  2858. if (taicpu(hp1).opcode = A_AND) and
  2859. (taicpu(p).oper[1]^.typ = top_reg) and
  2860. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2861. begin
  2862. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2863. begin
  2864. case taicpu(p).opsize of
  2865. S_L:
  2866. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2867. begin
  2868. { Optimize out:
  2869. mov x, %reg
  2870. and ffffffffh, %reg
  2871. }
  2872. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2873. RemoveInstruction(hp1);
  2874. Result:=true;
  2875. exit;
  2876. end;
  2877. S_Q: { TODO: Confirm if this is even possible }
  2878. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2879. begin
  2880. { Optimize out:
  2881. mov x, %reg
  2882. and ffffffffffffffffh, %reg
  2883. }
  2884. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2885. RemoveInstruction(hp1);
  2886. Result:=true;
  2887. exit;
  2888. end;
  2889. else
  2890. ;
  2891. end;
  2892. if (
  2893. (taicpu(p).oper[0]^.typ=top_reg) or
  2894. (
  2895. (taicpu(p).oper[0]^.typ=top_ref) and
  2896. (taicpu(p).oper[0]^.ref^.refaddr<>addr_full)
  2897. )
  2898. ) and
  2899. GetNextInstruction(hp1,hp2) and
  2900. MatchInstruction(hp2,A_TEST,[]) and
  2901. (
  2902. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) or
  2903. (
  2904. { If the register being tested is smaller than the one
  2905. that received a bitwise AND, permit it if the constant
  2906. fits into the smaller size }
  2907. (taicpu(hp1).oper[1]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  2908. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) and
  2909. (taicpu(hp1).oper[0]^.typ = top_const) and (taicpu(hp1).oper[0]^.val >= 0) and
  2910. (GetSubReg(taicpu(hp2).oper[1]^.reg) < GetSubReg(taicpu(hp1).oper[1]^.reg)) and
  2911. (
  2912. (
  2913. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBL) and
  2914. (taicpu(hp1).oper[0]^.val <= $FF)
  2915. ) or
  2916. (
  2917. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBW) and
  2918. (taicpu(hp1).oper[0]^.val <= $FFFF)
  2919. {$ifdef x86_64}
  2920. ) or
  2921. (
  2922. (GetSubReg(taicpu(hp2).oper[1]^.reg) = R_SUBD) and
  2923. (taicpu(hp1).oper[0]^.val <= $FFFFFFFF)
  2924. {$endif x86_64}
  2925. )
  2926. )
  2927. )
  2928. ) and
  2929. (
  2930. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2931. MatchOperand(taicpu(hp2).oper[0]^,-1)
  2932. ) and
  2933. GetNextInstruction(hp2,hp3) and
  2934. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2935. (taicpu(hp3).condition in [C_E,C_NE]) then
  2936. begin
  2937. TransferUsedRegs(TmpUsedRegs);
  2938. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2939. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2940. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2941. begin
  2942. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2943. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2944. taicpu(hp1).opcode:=A_TEST;
  2945. { Shrink the TEST instruction down to the smallest possible size }
  2946. case taicpu(hp1).oper[0]^.val of
  2947. 0..255:
  2948. if (taicpu(hp1).opsize <> S_B)
  2949. {$ifndef x86_64}
  2950. and (
  2951. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  2952. { Cannot encode byte-sized ESI, EDI, EBP or ESP under i386 }
  2953. (GetSupReg(taicpu(hp1).oper[1]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])
  2954. )
  2955. {$endif x86_64}
  2956. then
  2957. begin
  2958. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2959. { Only print debug message if the TEST instruction
  2960. is a different size before and after }
  2961. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testb to reduce instruction size (Test2Test 1a)' , p);
  2962. taicpu(hp1).opsize := S_B;
  2963. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2964. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBL);
  2965. end;
  2966. 256..65535:
  2967. if (taicpu(hp1).opsize <> S_W) then
  2968. begin
  2969. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2970. { Only print debug message if the TEST instruction
  2971. is a different size before and after }
  2972. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testw to reduce instruction size (Test2Test 1b)' , p);
  2973. taicpu(hp1).opsize := S_W;
  2974. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2975. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBW);
  2976. end;
  2977. {$ifdef x86_64}
  2978. 65536..$7FFFFFFF:
  2979. if (taicpu(hp1).opsize <> S_L) then
  2980. begin
  2981. if taicpu(hp1).opsize <> taicpu(hp2).opsize then
  2982. { Only print debug message if the TEST instruction
  2983. is a different size before and after }
  2984. DebugMsg(SPeepholeOptimization + 'test' + debug_opsize2str(taicpu(hp1).opsize) + ' -> testl to reduce instruction size (Test2Test 1c)' , p);
  2985. taicpu(hp1).opsize := S_L;
  2986. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2987. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  2988. end;
  2989. {$endif x86_64}
  2990. else
  2991. ;
  2992. end;
  2993. RemoveInstruction(hp2);
  2994. RemoveCurrentP(p, hp1);
  2995. Result:=true;
  2996. exit;
  2997. end;
  2998. end;
  2999. end
  3000. else if IsMOVZXAcceptable and
  3001. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  3002. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  3003. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  3004. then
  3005. begin
  3006. InputVal := debug_operstr(taicpu(p).oper[0]^);
  3007. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  3008. case taicpu(p).opsize of
  3009. S_B:
  3010. if (taicpu(hp1).oper[0]^.val = $ff) then
  3011. begin
  3012. { Convert:
  3013. movb x, %regl movb x, %regl
  3014. andw ffh, %regw andl ffh, %regd
  3015. To:
  3016. movzbw x, %regd movzbl x, %regd
  3017. (Identical registers, just different sizes)
  3018. }
  3019. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  3020. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  3021. case taicpu(hp1).opsize of
  3022. S_W: NewSize := S_BW;
  3023. S_L: NewSize := S_BL;
  3024. {$ifdef x86_64}
  3025. S_Q: NewSize := S_BQ;
  3026. {$endif x86_64}
  3027. else
  3028. InternalError(2018011510);
  3029. end;
  3030. end
  3031. else
  3032. NewSize := S_NO;
  3033. S_W:
  3034. if (taicpu(hp1).oper[0]^.val = $ffff) then
  3035. begin
  3036. { Convert:
  3037. movw x, %regw
  3038. andl ffffh, %regd
  3039. To:
  3040. movzwl x, %regd
  3041. (Identical registers, just different sizes)
  3042. }
  3043. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  3044. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  3045. case taicpu(hp1).opsize of
  3046. S_L: NewSize := S_WL;
  3047. {$ifdef x86_64}
  3048. S_Q: NewSize := S_WQ;
  3049. {$endif x86_64}
  3050. else
  3051. InternalError(2018011511);
  3052. end;
  3053. end
  3054. else
  3055. NewSize := S_NO;
  3056. else
  3057. NewSize := S_NO;
  3058. end;
  3059. if NewSize <> S_NO then
  3060. begin
  3061. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  3062. { The actual optimization }
  3063. taicpu(p).opcode := A_MOVZX;
  3064. taicpu(p).changeopsize(NewSize);
  3065. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  3066. { Safeguard if "and" is followed by a conditional command }
  3067. TransferUsedRegs(TmpUsedRegs);
  3068. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  3069. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  3070. begin
  3071. { At this point, the "and" command is effectively equivalent to
  3072. "test %reg,%reg". This will be handled separately by the
  3073. Peephole Optimizer. [Kit] }
  3074. DebugMsg(SPeepholeOptimization + PreMessage +
  3075. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3076. end
  3077. else
  3078. begin
  3079. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  3080. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  3081. RemoveInstruction(hp1);
  3082. end;
  3083. Result := True;
  3084. Exit;
  3085. end;
  3086. end;
  3087. end;
  3088. if (taicpu(hp1).opcode = A_OR) and
  3089. (taicpu(p).oper[1]^.typ = top_reg) and
  3090. MatchOperand(taicpu(p).oper[0]^, 0) and
  3091. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  3092. begin
  3093. { mov 0, %reg
  3094. or ###,%reg
  3095. Change to (only if the flags are not used):
  3096. mov ###,%reg
  3097. }
  3098. TransferUsedRegs(TmpUsedRegs);
  3099. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3100. DoOptimisation := True;
  3101. { Even if the flags are used, we might be able to do the optimisation
  3102. if the conditions are predictable }
  3103. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3104. begin
  3105. { Only perform if ### = %reg (the same register) or equal to 0,
  3106. so %reg is guaranteed to still have a value of zero }
  3107. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  3108. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  3109. begin
  3110. hp2 := hp1;
  3111. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3112. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  3113. GetNextInstruction(hp2, hp3) do
  3114. begin
  3115. { Don't continue modifying if the flags state is getting changed }
  3116. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  3117. Break;
  3118. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  3119. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  3120. begin
  3121. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  3122. begin
  3123. { Condition is always true }
  3124. case taicpu(hp3).opcode of
  3125. A_Jcc:
  3126. begin
  3127. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  3128. { Check for jump shortcuts before we destroy the condition }
  3129. DoJumpOptimizations(hp3, TempBool);
  3130. MakeUnconditional(taicpu(hp3));
  3131. Result := True;
  3132. end;
  3133. A_CMOVcc:
  3134. begin
  3135. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  3136. taicpu(hp3).opcode := A_MOV;
  3137. taicpu(hp3).condition := C_None;
  3138. Result := True;
  3139. end;
  3140. A_SETcc:
  3141. begin
  3142. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  3143. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  3144. taicpu(hp3).opcode := A_MOV;
  3145. taicpu(hp3).ops := 2;
  3146. taicpu(hp3).condition := C_None;
  3147. taicpu(hp3).opsize := S_B;
  3148. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3149. taicpu(hp3).loadconst(0, 1);
  3150. Result := True;
  3151. end;
  3152. else
  3153. InternalError(2021090701);
  3154. end;
  3155. end
  3156. 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
  3157. begin
  3158. { Condition is always false }
  3159. case taicpu(hp3).opcode of
  3160. A_Jcc:
  3161. begin
  3162. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  3163. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  3164. RemoveInstruction(hp3);
  3165. Result := True;
  3166. { Since hp3 was deleted, hp2 must not be updated }
  3167. Continue;
  3168. end;
  3169. A_CMOVcc:
  3170. begin
  3171. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  3172. RemoveInstruction(hp3);
  3173. Result := True;
  3174. { Since hp3 was deleted, hp2 must not be updated }
  3175. Continue;
  3176. end;
  3177. A_SETcc:
  3178. begin
  3179. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  3180. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  3181. taicpu(hp3).opcode := A_MOV;
  3182. taicpu(hp3).ops := 2;
  3183. taicpu(hp3).condition := C_None;
  3184. taicpu(hp3).opsize := S_B;
  3185. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  3186. taicpu(hp3).loadconst(0, 0);
  3187. Result := True;
  3188. end;
  3189. else
  3190. InternalError(2021090702);
  3191. end;
  3192. end
  3193. else
  3194. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  3195. DoOptimisation := False;
  3196. end;
  3197. hp2 := hp3;
  3198. end;
  3199. { Flags are still in use - don't optimise }
  3200. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  3201. DoOptimisation := False;
  3202. end
  3203. else
  3204. DoOptimisation := False;
  3205. end;
  3206. if DoOptimisation then
  3207. begin
  3208. {$ifdef x86_64}
  3209. { OR only supports 32-bit sign-extended constants for 64-bit
  3210. instructions, so compensate for this if the constant is
  3211. encoded as a value greater than or equal to 2^31 }
  3212. if (taicpu(hp1).opsize = S_Q) and
  3213. (taicpu(hp1).oper[0]^.typ = top_const) and
  3214. (taicpu(hp1).oper[0]^.val >= $80000000) then
  3215. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  3216. {$endif x86_64}
  3217. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  3218. taicpu(hp1).opcode := A_MOV;
  3219. RemoveCurrentP(p, hp1);
  3220. Result := True;
  3221. Exit;
  3222. end;
  3223. end;
  3224. { Next instruction is also a MOV ? }
  3225. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  3226. begin
  3227. if MatchOpType(taicpu(p), top_const, top_ref) and
  3228. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3229. TryConstMerge(p, hp1) then
  3230. begin
  3231. Result := True;
  3232. { In case we have four byte writes in a row, check for 2 more
  3233. right now so we don't have to wait for another iteration of
  3234. pass 1
  3235. }
  3236. { If two byte-writes were merged, the opsize is now S_W, not S_B }
  3237. case taicpu(p).opsize of
  3238. S_W:
  3239. begin
  3240. if GetNextInstruction(p, hp1) and
  3241. MatchInstruction(hp1, A_MOV, [S_B]) and
  3242. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3243. GetNextInstruction(hp1, hp2) and
  3244. MatchInstruction(hp2, A_MOV, [S_B]) and
  3245. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3246. { Try to merge the two bytes }
  3247. TryConstMerge(hp1, hp2) then
  3248. { Now try to merge the two words (hp2 will get deleted) }
  3249. TryConstMerge(p, hp1);
  3250. end;
  3251. S_L:
  3252. begin
  3253. { Though this only really benefits x86_64 and not i386, it
  3254. gets a potential optimisation done faster and hence
  3255. reduces the number of times OptPass1MOV is entered }
  3256. if GetNextInstruction(p, hp1) and
  3257. MatchInstruction(hp1, A_MOV, [S_W]) and
  3258. MatchOpType(taicpu(hp1), top_const, top_ref) and
  3259. GetNextInstruction(hp1, hp2) and
  3260. MatchInstruction(hp2, A_MOV, [S_W]) and
  3261. MatchOpType(taicpu(hp2), top_const, top_ref) and
  3262. { Try to merge the two words }
  3263. TryConstMerge(hp1, hp2) then
  3264. { This will always fail on i386, so don't bother
  3265. calling it unless we're doing x86_64 }
  3266. {$ifdef x86_64}
  3267. { Now try to merge the two longwords (hp2 will get deleted) }
  3268. TryConstMerge(p, hp1)
  3269. {$endif x86_64}
  3270. ;
  3271. end;
  3272. else
  3273. ;
  3274. end;
  3275. Exit;
  3276. end;
  3277. if (taicpu(p).oper[1]^.typ = top_reg) and
  3278. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  3279. begin
  3280. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3281. TransferUsedRegs(TmpUsedRegs);
  3282. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3283. { we have
  3284. mov x, %treg
  3285. mov %treg, y
  3286. }
  3287. if not(RegInOp(p_TargetReg, taicpu(hp1).oper[1]^)) then
  3288. if not(RegUsedAfterInstruction(p_TargetReg, hp1, TmpUsedRegs)) then
  3289. { we've got
  3290. mov x, %treg
  3291. mov %treg, y
  3292. with %treg is not used after }
  3293. case taicpu(p).oper[0]^.typ Of
  3294. { top_reg is covered by DeepMOVOpt }
  3295. top_const:
  3296. begin
  3297. { change
  3298. mov const, %treg
  3299. mov %treg, y
  3300. to
  3301. mov const, y
  3302. }
  3303. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  3304. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3305. begin
  3306. if taicpu(hp1).oper[1]^.typ=top_reg then
  3307. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3308. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  3309. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  3310. RemoveInstruction(hp1);
  3311. Result:=true;
  3312. Exit;
  3313. end;
  3314. end;
  3315. top_ref:
  3316. case taicpu(hp1).oper[1]^.typ of
  3317. top_reg:
  3318. begin
  3319. { change
  3320. mov mem, %treg
  3321. mov %treg, %reg
  3322. to
  3323. mov mem, %reg"
  3324. }
  3325. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3326. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  3327. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  3328. RemoveInstruction(hp1);
  3329. Result:=true;
  3330. Exit;
  3331. end;
  3332. top_ref:
  3333. begin
  3334. {$ifdef x86_64}
  3335. { Look for the following to simplify:
  3336. mov x(mem1), %reg
  3337. mov %reg, y(mem2)
  3338. mov x+8(mem1), %reg
  3339. mov %reg, y+8(mem2)
  3340. Change to:
  3341. movdqu x(mem1), %xmmreg
  3342. movdqu %xmmreg, y(mem2)
  3343. ...but only as long as the memory blocks don't overlap
  3344. }
  3345. SourceRef := taicpu(p).oper[0]^.ref^;
  3346. TargetRef := taicpu(hp1).oper[1]^.ref^;
  3347. if (taicpu(p).opsize = S_Q) and
  3348. GetNextInstruction(hp1, hp2) and
  3349. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3350. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  3351. begin
  3352. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  3353. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3354. Inc(SourceRef.offset, 8);
  3355. if UseAVX then
  3356. begin
  3357. MovAligned := A_VMOVDQA;
  3358. MovUnaligned := A_VMOVDQU;
  3359. end
  3360. else
  3361. begin
  3362. MovAligned := A_MOVDQA;
  3363. MovUnaligned := A_MOVDQU;
  3364. end;
  3365. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  3366. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 16) then
  3367. begin
  3368. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3369. Inc(TargetRef.offset, 8);
  3370. if GetNextInstruction(hp2, hp3) and
  3371. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3372. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3373. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3374. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3375. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3376. begin
  3377. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3378. if NewMMReg <> NR_NO then
  3379. begin
  3380. { Remember that the offsets are 8 ahead }
  3381. if ((SourceRef.offset mod 16) = 8) and
  3382. (
  3383. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3384. (SourceRef.base = current_procinfo.framepointer) or
  3385. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3386. ) then
  3387. taicpu(p).opcode := MovAligned
  3388. else
  3389. taicpu(p).opcode := MovUnaligned;
  3390. taicpu(p).opsize := S_XMM;
  3391. taicpu(p).oper[1]^.reg := NewMMReg;
  3392. if ((TargetRef.offset mod 16) = 8) and
  3393. (
  3394. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3395. (TargetRef.base = current_procinfo.framepointer) or
  3396. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3397. ) then
  3398. taicpu(hp1).opcode := MovAligned
  3399. else
  3400. taicpu(hp1).opcode := MovUnaligned;
  3401. taicpu(hp1).opsize := S_XMM;
  3402. taicpu(hp1).oper[0]^.reg := NewMMReg;
  3403. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 1)', p);
  3404. RemoveInstruction(hp2);
  3405. RemoveInstruction(hp3);
  3406. Result := True;
  3407. Exit;
  3408. end;
  3409. end;
  3410. end
  3411. else
  3412. begin
  3413. { See if the next references are 8 less rather than 8 greater }
  3414. Dec(SourceRef.offset, 16); { -8 the other way }
  3415. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  3416. begin
  3417. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  3418. Dec(TargetRef.offset, 8); { Only 8, not 16, as it wasn't incremented unlike SourceRef }
  3419. if not RefsMightOverlap(SourceRef, TargetRef, 16) and
  3420. GetNextInstruction(hp2, hp3) and
  3421. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  3422. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  3423. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  3424. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  3425. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  3426. begin
  3427. NewMMReg := GetMMRegisterBetween(R_SUBMMX, UsedRegs, p, hp3);
  3428. if NewMMReg <> NR_NO then
  3429. begin
  3430. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  3431. if ((SourceRef.offset mod 16) = 0) and
  3432. (
  3433. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3434. (SourceRef.base = current_procinfo.framepointer) or
  3435. ((SourceRef.alignment >= 16) and ((SourceRef.alignment mod 16) = 0))
  3436. ) then
  3437. taicpu(hp2).opcode := MovAligned
  3438. else
  3439. taicpu(hp2).opcode := MovUnaligned;
  3440. taicpu(hp2).opsize := S_XMM;
  3441. taicpu(hp2).oper[1]^.reg := NewMMReg;
  3442. if ((TargetRef.offset mod 16) = 0) and
  3443. (
  3444. { Base pointer is always aligned (stack pointer won't be if there's no stack frame) }
  3445. (TargetRef.base = current_procinfo.framepointer) or
  3446. ((TargetRef.alignment >= 16) and ((TargetRef.alignment mod 16) = 0))
  3447. ) then
  3448. taicpu(hp3).opcode := MovAligned
  3449. else
  3450. taicpu(hp3).opcode := MovUnaligned;
  3451. taicpu(hp3).opsize := S_XMM;
  3452. taicpu(hp3).oper[0]^.reg := NewMMReg;
  3453. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(NewMMReg) + ' to merge a pair of memory moves (MovMovMovMov2MovdqMovdq 2)', p);
  3454. RemoveInstruction(hp1);
  3455. RemoveCurrentP(p, hp2);
  3456. Result := True;
  3457. Exit;
  3458. end;
  3459. end;
  3460. end;
  3461. end;
  3462. end;
  3463. {$endif x86_64}
  3464. end;
  3465. else
  3466. { The write target should be a reg or a ref }
  3467. InternalError(2021091601);
  3468. end;
  3469. else
  3470. ;
  3471. end
  3472. else
  3473. { %treg is used afterwards, but all eventualities
  3474. other than the first MOV instruction being a constant
  3475. are covered by DeepMOVOpt, so only check for that }
  3476. if (taicpu(p).oper[0]^.typ = top_const) and
  3477. (
  3478. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  3479. not (cs_opt_size in current_settings.optimizerswitches) or
  3480. (taicpu(hp1).opsize = S_B)
  3481. ) and
  3482. (
  3483. (taicpu(hp1).oper[1]^.typ = top_reg) or
  3484. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  3485. ) then
  3486. begin
  3487. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  3488. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  3489. end;
  3490. end;
  3491. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3492. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3493. { mov reg1, mem1 or mov mem1, reg1
  3494. mov mem2, reg2 mov reg2, mem2}
  3495. begin
  3496. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3497. { mov reg1, mem1 or mov mem1, reg1
  3498. mov mem2, reg1 mov reg2, mem1}
  3499. begin
  3500. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3501. { Removes the second statement from
  3502. mov reg1, mem1/reg2
  3503. mov mem1/reg2, reg1 }
  3504. begin
  3505. if taicpu(p).oper[0]^.typ=top_reg then
  3506. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3507. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  3508. RemoveInstruction(hp1);
  3509. Result:=true;
  3510. exit;
  3511. end
  3512. else
  3513. begin
  3514. TransferUsedRegs(TmpUsedRegs);
  3515. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3516. if (taicpu(p).oper[1]^.typ = top_ref) and
  3517. { mov reg1, mem1
  3518. mov mem2, reg1 }
  3519. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  3520. GetNextInstruction(hp1, hp2) and
  3521. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  3522. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  3523. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  3524. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  3525. { change to
  3526. mov reg1, mem1 mov reg1, mem1
  3527. mov mem2, reg1 cmp reg1, mem2
  3528. cmp mem1, reg1
  3529. }
  3530. begin
  3531. RemoveInstruction(hp2);
  3532. taicpu(hp1).opcode := A_CMP;
  3533. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  3534. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3535. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3536. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  3537. end;
  3538. end;
  3539. end
  3540. else if (taicpu(p).oper[1]^.typ=top_ref) and
  3541. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3542. begin
  3543. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  3544. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  3545. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  3546. end
  3547. else
  3548. begin
  3549. TransferUsedRegs(TmpUsedRegs);
  3550. if GetNextInstruction(hp1, hp2) and
  3551. MatchOpType(taicpu(p),top_ref,top_reg) and
  3552. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3553. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3554. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  3555. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  3556. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3557. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  3558. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  3559. { mov mem1, %reg1
  3560. mov %reg1, mem2
  3561. mov mem2, reg2
  3562. to:
  3563. mov mem1, reg2
  3564. mov reg2, mem2}
  3565. begin
  3566. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  3567. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  3568. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  3569. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  3570. RemoveInstruction(hp2);
  3571. Result := True;
  3572. end
  3573. {$ifdef i386}
  3574. { this is enabled for i386 only, as the rules to create the reg sets below
  3575. are too complicated for x86-64, so this makes this code too error prone
  3576. on x86-64
  3577. }
  3578. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  3579. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  3580. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  3581. { mov mem1, reg1 mov mem1, reg1
  3582. mov reg1, mem2 mov reg1, mem2
  3583. mov mem2, reg2 mov mem2, reg1
  3584. to: to:
  3585. mov mem1, reg1 mov mem1, reg1
  3586. mov mem1, reg2 mov reg1, mem2
  3587. mov reg1, mem2
  3588. or (if mem1 depends on reg1
  3589. and/or if mem2 depends on reg2)
  3590. to:
  3591. mov mem1, reg1
  3592. mov reg1, mem2
  3593. mov reg1, reg2
  3594. }
  3595. begin
  3596. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  3597. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  3598. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  3599. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  3600. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3601. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3602. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3603. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  3604. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  3605. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  3606. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  3607. end
  3608. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  3609. begin
  3610. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  3611. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  3612. end
  3613. else
  3614. begin
  3615. RemoveInstruction(hp2);
  3616. end
  3617. {$endif i386}
  3618. ;
  3619. end;
  3620. end
  3621. { movl [mem1],reg1
  3622. movl [mem1],reg2
  3623. to
  3624. movl [mem1],reg1
  3625. movl reg1,reg2
  3626. }
  3627. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  3628. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  3629. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3630. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  3631. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  3632. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  3633. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  3634. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  3635. begin
  3636. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  3637. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  3638. end;
  3639. { movl const1,[mem1]
  3640. movl [mem1],reg1
  3641. to
  3642. movl const1,reg1
  3643. movl reg1,[mem1]
  3644. }
  3645. if MatchOpType(Taicpu(p),top_const,top_ref) and
  3646. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  3647. (taicpu(p).opsize = taicpu(hp1).opsize) and
  3648. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  3649. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  3650. begin
  3651. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  3652. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  3653. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  3654. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  3655. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  3656. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  3657. Result:=true;
  3658. exit;
  3659. end;
  3660. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  3661. { Change:
  3662. movl %reg1,%reg2
  3663. movl x(%reg1),%reg1 (If something other than %reg1 is written to, DeepMOVOpt would have caught it)
  3664. movl x(%reg2),%regX (%regX can be %reg2 or something else)
  3665. To:
  3666. movl %reg1,%reg2 (if %regX = %reg2, then remove this instruction)
  3667. movl x(%reg1),%reg1
  3668. movl %reg1,%regX
  3669. }
  3670. if MatchOpType(taicpu(p), top_reg, top_reg) then
  3671. begin
  3672. p_SourceReg := taicpu(p).oper[0]^.reg;
  3673. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3674. if (taicpu(hp1).oper[0]^.typ = top_ref) { The other operand will be a register } and
  3675. (taicpu(hp1).oper[1]^.reg = p_SourceReg) and
  3676. RegInRef(p_SourceReg, taicpu(hp1).oper[0]^.ref^) and
  3677. GetNextInstruction(hp1, hp2) and
  3678. MatchInstruction(hp2, A_MOV, [taicpu(p).opsize]) and
  3679. (taicpu(hp2).oper[0]^.typ = top_ref) { The other operand will be a register } then
  3680. begin
  3681. SourceRef := taicpu(hp2).oper[0]^.ref^;
  3682. if RegInRef(p_TargetReg, SourceRef) and
  3683. { If %reg1 also appears in the second reference, then it will
  3684. not refer to the same memory block as the first reference }
  3685. not RegInRef(p_SourceReg, SourceRef) then
  3686. begin
  3687. { Check to see if the references match if %reg2 is changed to %reg1 }
  3688. if SourceRef.base = p_TargetReg then
  3689. SourceRef.base := p_SourceReg;
  3690. if SourceRef.index = p_TargetReg then
  3691. SourceRef.index := p_SourceReg;
  3692. { RefsEqual also checks to ensure both references are non-volatile }
  3693. if RefsEqual(taicpu(hp1).oper[0]^.ref^, SourceRef) then
  3694. begin
  3695. taicpu(hp2).loadreg(0, p_SourceReg);
  3696. DebugMsg(SPeepholeOptimization + 'Optimised register duplication and memory read (MovMovMov2MovMovMov)', p);
  3697. Result := True;
  3698. if taicpu(hp2).oper[1]^.reg = p_TargetReg then
  3699. begin
  3700. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5a done', p);
  3701. RemoveCurrentP(p, hp1);
  3702. Exit;
  3703. end
  3704. else
  3705. begin
  3706. { Check to see if %reg2 is no longer in use }
  3707. TransferUsedRegs(TmpUsedRegs);
  3708. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3709. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3710. if not RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs) then
  3711. begin
  3712. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5b done', p);
  3713. RemoveCurrentP(p, hp1);
  3714. Exit;
  3715. end;
  3716. end;
  3717. { If we reach this point, p and hp1 weren't actually modified,
  3718. so we can do a bit more work on this pass }
  3719. end;
  3720. end;
  3721. end;
  3722. end;
  3723. end;
  3724. { search further than the next instruction for a mov (as long as it's not a jump) }
  3725. if not is_calljmpuncondret(taicpu(hp1).opcode) and
  3726. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  3727. (taicpu(p).oper[1]^.typ = top_reg) and
  3728. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  3729. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  3730. begin
  3731. { we work with hp2 here, so hp1 can be still used later on when
  3732. checking for GetNextInstruction_p }
  3733. hp3 := hp1;
  3734. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  3735. CrossJump := (taicpu(hp1).opcode = A_Jcc);
  3736. { Remember that p_TargetReg contains taicpu(p).oper[1]^.reg }
  3737. TransferUsedRegs(TmpUsedRegs);
  3738. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3739. if NotFirstIteration then
  3740. JumpTracking := TLinkedList.Create
  3741. else
  3742. JumpTracking := nil;
  3743. while GetNextInstructionUsingRegCond(hp3,hp2,p_TargetReg,JumpTracking,CrossJump) and
  3744. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  3745. (hp2.typ=ait_instruction) do
  3746. begin
  3747. case taicpu(hp2).opcode of
  3748. A_POP:
  3749. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) then
  3750. begin
  3751. if not CrossJump and
  3752. not RegUsedBetween(p_TargetReg, p, hp2) then
  3753. begin
  3754. { We can remove the original MOV since the register
  3755. wasn't used between it and its popping from the stack }
  3756. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3c done',p);
  3757. RemoveCurrentp(p, hp1);
  3758. Result := True;
  3759. JumpTracking.Free;
  3760. Exit;
  3761. end;
  3762. { Can't go any further }
  3763. Break;
  3764. end;
  3765. A_MOV:
  3766. if MatchOperand(taicpu(hp2).oper[0]^,p_TargetReg) and
  3767. ((taicpu(p).oper[0]^.typ=top_const) or
  3768. ((taicpu(p).oper[0]^.typ=top_reg) and
  3769. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  3770. )
  3771. ) then
  3772. begin
  3773. { we have
  3774. mov x, %treg
  3775. mov %treg, y
  3776. }
  3777. { We don't need to call UpdateUsedRegs for every instruction between
  3778. p and hp2 because the register we're concerned about will not
  3779. become deallocated (otherwise GetNextInstructionUsingReg would
  3780. have stopped at an earlier instruction). [Kit] }
  3781. TempRegUsed :=
  3782. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  3783. RegReadByInstruction(p_TargetReg, hp3) or
  3784. RegUsedAfterInstruction(p_TargetReg, hp2, TmpUsedRegs);
  3785. case taicpu(p).oper[0]^.typ Of
  3786. top_reg:
  3787. begin
  3788. { change
  3789. mov %reg, %treg
  3790. mov %treg, y
  3791. to
  3792. mov %reg, y
  3793. }
  3794. p_SourceReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  3795. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3796. if MatchOperand(taicpu(hp2).oper[1]^, p_SourceReg) then
  3797. begin
  3798. { %reg = y - remove hp2 completely (doing it here instead of relying on
  3799. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  3800. if TempRegUsed then
  3801. begin
  3802. DebugMsg(SPeepholeOptimization + debug_regname(p_SourceReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  3803. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3804. { Set the start of the next GetNextInstructionUsingRegCond search
  3805. to start at the entry right before hp2 (which is about to be removed) }
  3806. hp3 := tai(hp2.Previous);
  3807. RemoveInstruction(hp2);
  3808. { See if there's more we can optimise }
  3809. Continue;
  3810. end
  3811. else
  3812. begin
  3813. RemoveInstruction(hp2);
  3814. { We can remove the original MOV too }
  3815. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  3816. RemoveCurrentP(p, hp1);
  3817. Result:=true;
  3818. JumpTracking.Free;
  3819. Exit;
  3820. end;
  3821. end
  3822. else
  3823. begin
  3824. AllocRegBetween(p_SourceReg, p, hp2, UsedRegs);
  3825. taicpu(hp2).loadReg(0, p_SourceReg);
  3826. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(p_SourceReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  3827. { Check to see if the register also appears in the reference }
  3828. if (taicpu(hp2).oper[1]^.typ = top_ref) then
  3829. ReplaceRegisterInRef(taicpu(hp2).oper[1]^.ref^, p_TargetReg, p_SourceReg);
  3830. { Don't remove the first instruction if the temporary register is in use }
  3831. if not TempRegUsed and
  3832. { ReplaceRegisterInRef won't actually replace the register if it's a different size }
  3833. not RegInOp(p_TargetReg, taicpu(hp2).oper[1]^) then
  3834. begin
  3835. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  3836. RemoveCurrentP(p, hp1);
  3837. Result:=true;
  3838. JumpTracking.Free;
  3839. Exit;
  3840. end;
  3841. { No need to set Result to True here. If there's another instruction later
  3842. on that can be optimised, it will be detected when the main Pass 1 loop
  3843. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] }
  3844. end;
  3845. end;
  3846. top_const:
  3847. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  3848. begin
  3849. { change
  3850. mov const, %treg
  3851. mov %treg, y
  3852. to
  3853. mov const, y
  3854. }
  3855. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  3856. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  3857. begin
  3858. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  3859. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  3860. if TempRegUsed then
  3861. begin
  3862. { Don't remove the first instruction if the temporary register is in use }
  3863. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  3864. { No need to set Result to True. If there's another instruction later on
  3865. that can be optimised, it will be detected when the main Pass 1 loop
  3866. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  3867. end
  3868. else
  3869. begin
  3870. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  3871. RemoveCurrentP(p, hp1);
  3872. Result:=true;
  3873. Exit;
  3874. end;
  3875. end;
  3876. end;
  3877. else
  3878. Internalerror(2019103001);
  3879. end;
  3880. end
  3881. else
  3882. if MatchOperand(taicpu(hp2).oper[1]^, p_TargetReg) then
  3883. begin
  3884. if not CrossJump and
  3885. not RegUsedBetween(p_TargetReg, p, hp2) and
  3886. not RegReadByInstruction(p_TargetReg, hp2) then
  3887. begin
  3888. { Register is not used before it is overwritten }
  3889. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3a done',p);
  3890. RemoveCurrentp(p, hp1);
  3891. Result := True;
  3892. Exit;
  3893. end;
  3894. if (taicpu(p).oper[0]^.typ = top_const) and
  3895. (taicpu(hp2).oper[0]^.typ = top_const) then
  3896. begin
  3897. if taicpu(p).oper[0]^.val = taicpu(hp2).oper[0]^.val then
  3898. begin
  3899. { Same value - register hasn't changed }
  3900. DebugMsg(SPeepholeOptimization + 'Mov2Nop 2 done', hp2);
  3901. RemoveInstruction(hp2);
  3902. Result := True;
  3903. { See if there's more we can optimise }
  3904. Continue;
  3905. end;
  3906. end;
  3907. end;
  3908. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  3909. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  3910. MatchOperand(taicpu(hp2).oper[0]^, p_TargetReg) and
  3911. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, p_TargetReg) then
  3912. begin
  3913. {
  3914. Change from:
  3915. mov ###, %reg
  3916. ...
  3917. movs/z %reg,%reg (Same register, just different sizes)
  3918. To:
  3919. movs/z ###, %reg (Longer version)
  3920. ...
  3921. (remove)
  3922. }
  3923. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  3924. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  3925. { Keep the first instruction as mov if ### is a constant }
  3926. if taicpu(p).oper[0]^.typ = top_const then
  3927. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  3928. else
  3929. begin
  3930. taicpu(p).opcode := taicpu(hp2).opcode;
  3931. taicpu(p).opsize := taicpu(hp2).opsize;
  3932. end;
  3933. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  3934. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  3935. RemoveInstruction(hp2);
  3936. Result := True;
  3937. JumpTracking.Free;
  3938. Exit;
  3939. end;
  3940. else
  3941. { Move down to the MatchOpType if-block below };
  3942. end;
  3943. { Also catches MOV/S/Z instructions that aren't modified }
  3944. if taicpu(p).oper[0]^.typ = top_reg then
  3945. begin
  3946. p_SourceReg := taicpu(p).oper[0]^.reg;
  3947. if
  3948. not RegModifiedByInstruction(p_SourceReg, hp3) and
  3949. not RegModifiedBetween(p_SourceReg, hp3, hp2) and
  3950. DeepMOVOpt(taicpu(p), taicpu(hp2)) then
  3951. begin
  3952. Result := True;
  3953. { Just in case something didn't get modified (e.g. an
  3954. implicit register). Also, if it does read from this
  3955. register, then there's no longer an advantage to
  3956. changing the register on subsequent instructions.}
  3957. if not RegReadByInstruction(p_TargetReg, hp2) then
  3958. begin
  3959. { If a conditional jump was crossed, do not delete
  3960. the original MOV no matter what }
  3961. if not CrossJump and
  3962. { RegEndOfLife returns True if the register is
  3963. deallocated before the next instruction or has
  3964. been loaded with a new value }
  3965. RegEndOfLife(p_TargetReg, taicpu(hp2)) then
  3966. begin
  3967. { We can remove the original MOV }
  3968. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  3969. RemoveCurrentp(p, hp1);
  3970. JumpTracking.Free;
  3971. Result := True;
  3972. Exit;
  3973. end;
  3974. if not RegModifiedByInstruction(p_TargetReg, hp2) then
  3975. begin
  3976. { See if there's more we can optimise }
  3977. hp3 := hp2;
  3978. Continue;
  3979. end;
  3980. end;
  3981. end;
  3982. end;
  3983. { Break out of the while loop under normal circumstances }
  3984. Break;
  3985. end;
  3986. JumpTracking.Free;
  3987. end;
  3988. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  3989. (taicpu(p).oper[1]^.typ = top_reg) and
  3990. (taicpu(p).opsize = S_L) and
  3991. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  3992. (hp2.typ = ait_instruction) and
  3993. (taicpu(hp2).opcode = A_AND) and
  3994. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  3995. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3996. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  3997. ) then
  3998. begin
  3999. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  4000. begin
  4001. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  4002. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  4003. begin
  4004. { Optimize out:
  4005. mov x, %reg
  4006. and ffffffffh, %reg
  4007. }
  4008. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  4009. RemoveInstruction(hp2);
  4010. Result:=true;
  4011. exit;
  4012. end;
  4013. end;
  4014. end;
  4015. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  4016. x >= RetOffset) as it doesn't do anything (it writes either to a
  4017. parameter or to the temporary storage room for the function
  4018. result)
  4019. }
  4020. if IsExitCode(hp1) and
  4021. (taicpu(p).oper[1]^.typ = top_ref) and
  4022. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  4023. (
  4024. (
  4025. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  4026. not (
  4027. assigned(current_procinfo.procdef.funcretsym) and
  4028. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  4029. )
  4030. ) or
  4031. { Also discard writes to the stack that are below the base pointer,
  4032. as this is temporary storage rather than a function result on the
  4033. stack, say. }
  4034. (
  4035. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  4036. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  4037. )
  4038. ) then
  4039. begin
  4040. RemoveCurrentp(p, hp1);
  4041. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  4042. RemoveLastDeallocForFuncRes(p);
  4043. Result:=true;
  4044. exit;
  4045. end;
  4046. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  4047. begin
  4048. if MatchOpType(taicpu(p),top_reg,top_ref) and
  4049. (taicpu(hp1).oper[1]^.typ = top_ref) and
  4050. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  4051. begin
  4052. { change
  4053. mov reg1, mem1
  4054. test/cmp x, mem1
  4055. to
  4056. mov reg1, mem1
  4057. test/cmp x, reg1
  4058. }
  4059. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  4060. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  4061. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4062. Result := True;
  4063. Exit;
  4064. end;
  4065. if DoMovCmpMemOpt(p, hp1, True) then
  4066. begin
  4067. Result := True;
  4068. Exit;
  4069. end;
  4070. end;
  4071. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4072. { If the flags register is in use, don't change the instruction to an
  4073. ADD otherwise this will scramble the flags. [Kit] }
  4074. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  4075. begin
  4076. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  4077. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  4078. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  4079. ) or
  4080. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  4081. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  4082. )
  4083. ) then
  4084. { mov reg1,ref
  4085. lea reg2,[reg1,reg2]
  4086. to
  4087. add reg2,ref}
  4088. begin
  4089. TransferUsedRegs(TmpUsedRegs);
  4090. { reg1 may not be used afterwards }
  4091. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4092. begin
  4093. Taicpu(hp1).opcode:=A_ADD;
  4094. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  4095. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  4096. RemoveCurrentp(p, hp1);
  4097. result:=true;
  4098. exit;
  4099. end;
  4100. end;
  4101. { If the LEA instruction can be converted into an arithmetic instruction,
  4102. it may be possible to then fold it in the next optimisation, otherwise
  4103. there's nothing more that can be optimised here. }
  4104. if not ConvertLEA(taicpu(hp1)) then
  4105. Exit;
  4106. end;
  4107. if (taicpu(p).oper[1]^.typ = top_reg) and
  4108. (hp1.typ = ait_instruction) and
  4109. GetNextInstruction(hp1, hp2) and
  4110. MatchInstruction(hp2,A_MOV,[]) and
  4111. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  4112. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  4113. (
  4114. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  4115. {$ifdef x86_64}
  4116. or
  4117. (
  4118. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  4119. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  4120. )
  4121. {$endif x86_64}
  4122. ) then
  4123. begin
  4124. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  4125. (taicpu(hp2).oper[0]^.typ=top_reg) then
  4126. { change movsX/movzX reg/ref, reg2
  4127. add/sub/or/... reg3/$const, reg2
  4128. mov reg2 reg/ref
  4129. dealloc reg2
  4130. to
  4131. add/sub/or/... reg3/$const, reg/ref }
  4132. begin
  4133. TransferUsedRegs(TmpUsedRegs);
  4134. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4135. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4136. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4137. begin
  4138. { by example:
  4139. movswl %si,%eax movswl %si,%eax p
  4140. decl %eax addl %edx,%eax hp1
  4141. movw %ax,%si movw %ax,%si hp2
  4142. ->
  4143. movswl %si,%eax movswl %si,%eax p
  4144. decw %eax addw %edx,%eax hp1
  4145. movw %ax,%si movw %ax,%si hp2
  4146. }
  4147. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  4148. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4149. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4150. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4151. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4152. {
  4153. ->
  4154. movswl %si,%eax movswl %si,%eax p
  4155. decw %si addw %dx,%si hp1
  4156. movw %ax,%si movw %ax,%si hp2
  4157. }
  4158. case taicpu(hp1).ops of
  4159. 1:
  4160. begin
  4161. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4162. if taicpu(hp1).oper[0]^.typ=top_reg then
  4163. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4164. end;
  4165. 2:
  4166. begin
  4167. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4168. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4169. (taicpu(hp1).opcode<>A_SHL) and
  4170. (taicpu(hp1).opcode<>A_SHR) and
  4171. (taicpu(hp1).opcode<>A_SAR) then
  4172. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4173. end;
  4174. else
  4175. internalerror(2008042701);
  4176. end;
  4177. {
  4178. ->
  4179. decw %si addw %dx,%si p
  4180. }
  4181. RemoveInstruction(hp2);
  4182. RemoveCurrentP(p, hp1);
  4183. Result:=True;
  4184. Exit;
  4185. end;
  4186. end;
  4187. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4188. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  4189. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  4190. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  4191. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  4192. )
  4193. {$ifdef i386}
  4194. { byte registers of esi, edi, ebp, esp are not available on i386 }
  4195. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4196. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  4197. {$endif i386}
  4198. then
  4199. { change movsX/movzX reg/ref, reg2
  4200. add/sub/or/... regX/$const, reg2
  4201. mov reg2, reg3
  4202. dealloc reg2
  4203. to
  4204. movsX/movzX reg/ref, reg3
  4205. add/sub/or/... reg3/$const, reg3
  4206. }
  4207. begin
  4208. TransferUsedRegs(TmpUsedRegs);
  4209. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4210. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4211. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  4212. begin
  4213. { by example:
  4214. movswl %si,%eax movswl %si,%eax p
  4215. decl %eax addl %edx,%eax hp1
  4216. movw %ax,%si movw %ax,%si hp2
  4217. ->
  4218. movswl %si,%eax movswl %si,%eax p
  4219. decw %eax addw %edx,%eax hp1
  4220. movw %ax,%si movw %ax,%si hp2
  4221. }
  4222. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  4223. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  4224. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  4225. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  4226. { limit size of constants as well to avoid assembler errors, but
  4227. check opsize to avoid overflow when left shifting the 1 }
  4228. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  4229. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  4230. {$ifdef x86_64}
  4231. { Be careful of, for example:
  4232. movl %reg1,%reg2
  4233. addl %reg3,%reg2
  4234. movq %reg2,%reg4
  4235. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  4236. }
  4237. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  4238. begin
  4239. taicpu(hp2).changeopsize(S_L);
  4240. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  4241. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  4242. end;
  4243. {$endif x86_64}
  4244. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  4245. taicpu(p).changeopsize(taicpu(hp2).opsize);
  4246. if taicpu(p).oper[0]^.typ=top_reg then
  4247. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4248. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  4249. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  4250. {
  4251. ->
  4252. movswl %si,%eax movswl %si,%eax p
  4253. decw %si addw %dx,%si hp1
  4254. movw %ax,%si movw %ax,%si hp2
  4255. }
  4256. case taicpu(hp1).ops of
  4257. 1:
  4258. begin
  4259. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  4260. if taicpu(hp1).oper[0]^.typ=top_reg then
  4261. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4262. end;
  4263. 2:
  4264. begin
  4265. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  4266. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  4267. (taicpu(hp1).opcode<>A_SHL) and
  4268. (taicpu(hp1).opcode<>A_SHR) and
  4269. (taicpu(hp1).opcode<>A_SAR) then
  4270. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  4271. end;
  4272. else
  4273. internalerror(2018111801);
  4274. end;
  4275. {
  4276. ->
  4277. decw %si addw %dx,%si p
  4278. }
  4279. RemoveInstruction(hp2);
  4280. end;
  4281. end;
  4282. end;
  4283. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  4284. GetNextInstruction(hp1, hp2) and
  4285. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  4286. MatchOperand(Taicpu(p).oper[0]^,0) and
  4287. (Taicpu(p).oper[1]^.typ = top_reg) and
  4288. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4289. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  4290. { mov reg1,0
  4291. bts reg1,operand1 --> mov reg1,operand2
  4292. or reg1,operand2 bts reg1,operand1}
  4293. begin
  4294. Taicpu(hp2).opcode:=A_MOV;
  4295. DebugMsg(SPeepholeOptimization + 'MovBtsOr2MovBts done',hp1);
  4296. asml.remove(hp1);
  4297. insertllitem(hp2,hp2.next,hp1);
  4298. RemoveCurrentp(p, hp1);
  4299. Result:=true;
  4300. exit;
  4301. end;
  4302. if MatchInstruction(hp1,A_SUB,[Taicpu(p).opsize]) and
  4303. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  4304. GetNextInstruction(hp1, hp2) and
  4305. MatchInstruction(hp2,A_CMP,[Taicpu(p).opsize]) and
  4306. MatchOperand(Taicpu(p).oper[0]^,Taicpu(hp2).oper[1]^) and
  4307. MatchOperand(Taicpu(hp1).oper[0]^,Taicpu(hp2).oper[0]^) then
  4308. { change
  4309. mov reg1,reg2
  4310. sub reg3,reg2
  4311. cmp reg3,reg1
  4312. into
  4313. mov reg1,reg2
  4314. sub reg3,reg2
  4315. }
  4316. begin
  4317. DebugMsg(SPeepholeOptimization + 'MovSubCmp2MovSub done',p);
  4318. RemoveInstruction(hp2);
  4319. Result:=true;
  4320. exit;
  4321. end;
  4322. {
  4323. mov ref,reg0
  4324. <op> reg0,reg1
  4325. dealloc reg0
  4326. to
  4327. <op> ref,reg1
  4328. }
  4329. if MatchOpType(taicpu(p),top_ref,top_reg) and
  4330. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4331. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4332. MatchInstruction(hp1,[A_AND,A_OR,A_XOR,A_ADD,A_SUB,A_CMP],[Taicpu(p).opsize]) and
  4333. not(MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^)) and
  4334. RegEndOfLife(taicpu(p).oper[1]^.reg,taicpu(hp1)) then
  4335. begin
  4336. taicpu(hp1).loadoper(0,taicpu(p).oper[0]^);
  4337. DebugMsg(SPeepholeOptimization + 'MovOp2Op done',hp1);
  4338. RemoveCurrentp(p, hp1);
  4339. Result:=true;
  4340. exit;
  4341. end;
  4342. if (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  4343. MatchInstruction(hp1, A_SHR, A_SAR, [taicpu(p).opsize]) and
  4344. MatchOpType(taicpu(hp1), top_const, top_reg) and
  4345. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  4346. begin
  4347. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  4348. {$ifdef x86_64}
  4349. { Convert:
  4350. movq x(ref),%reg64
  4351. shrq y,%reg64
  4352. To:
  4353. movl x+4(ref),%reg32
  4354. shrl y-32,%reg32 (Remove if y = 32)
  4355. }
  4356. if (taicpu(p).opsize = S_Q) and
  4357. (taicpu(hp1).opcode = A_SHR) and
  4358. (taicpu(hp1).oper[0]^.val >= 32) then
  4359. begin
  4360. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4361. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  4362. { Convert to 32-bit }
  4363. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  4364. taicpu(p).opsize := S_L;
  4365. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  4366. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  4367. if (taicpu(hp1).oper[0]^.val = 32) then
  4368. begin
  4369. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  4370. RemoveInstruction(hp1);
  4371. end
  4372. else
  4373. begin
  4374. { This will potentially open up more arithmetic operations since
  4375. the peephole optimizer now has a big hint that only the lower
  4376. 32 bits are currently in use (and opcodes are smaller in size) }
  4377. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  4378. taicpu(hp1).opsize := S_L;
  4379. Dec(taicpu(hp1).oper[0]^.val, 32);
  4380. DebugMsg(SPeepholeOptimization + PreMessage +
  4381. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  4382. end;
  4383. Result := True;
  4384. Exit;
  4385. end;
  4386. {$endif x86_64}
  4387. { Convert:
  4388. movl x(ref),%reg
  4389. shrl $24,%reg
  4390. To:
  4391. movzbl x+3(ref),%reg
  4392. Do similar things for movl; shrl $16 -> movzwl and movw; shrw $8 -> movzbw
  4393. Also accept sar instead of shr, but convert to movsx instead of movzx
  4394. }
  4395. if taicpu(hp1).opcode = A_SHR then
  4396. MovUnaligned := A_MOVZX
  4397. else
  4398. MovUnaligned := A_MOVSX;
  4399. NewSize := S_NO;
  4400. NewOffset := 0;
  4401. case taicpu(p).opsize of
  4402. S_B:
  4403. { No valid combinations };
  4404. S_W:
  4405. if (taicpu(hp1).oper[0]^.val = 8) then
  4406. begin
  4407. NewSize := S_BW;
  4408. NewOffset := 1;
  4409. end;
  4410. S_L:
  4411. case taicpu(hp1).oper[0]^.val of
  4412. 16:
  4413. begin
  4414. NewSize := S_WL;
  4415. NewOffset := 2;
  4416. end;
  4417. 24:
  4418. begin
  4419. NewSize := S_BL;
  4420. NewOffset := 3;
  4421. end;
  4422. else
  4423. ;
  4424. end;
  4425. {$ifdef x86_64}
  4426. S_Q:
  4427. case taicpu(hp1).oper[0]^.val of
  4428. 32:
  4429. begin
  4430. if taicpu(hp1).opcode = A_SAR then
  4431. begin
  4432. { 32-bit to 64-bit is a distinct instruction }
  4433. MovUnaligned := A_MOVSXD;
  4434. NewSize := S_LQ;
  4435. NewOffset := 4;
  4436. end
  4437. else
  4438. { Should have been handled by MovShr2Mov above }
  4439. InternalError(2022081811);
  4440. end;
  4441. 48:
  4442. begin
  4443. NewSize := S_WQ;
  4444. NewOffset := 6;
  4445. end;
  4446. 56:
  4447. begin
  4448. NewSize := S_BQ;
  4449. NewOffset := 7;
  4450. end;
  4451. else
  4452. ;
  4453. end;
  4454. {$endif x86_64}
  4455. else
  4456. InternalError(2022081810);
  4457. end;
  4458. if (NewSize <> S_NO) and
  4459. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFF - NewOffset) then
  4460. begin
  4461. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  4462. 'shr' + debug_opsize2str(taicpu(p).opsize) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> ' +
  4463. debug_op2str(MovUnaligned);
  4464. {$ifdef x86_64}
  4465. if MovUnaligned <> A_MOVSXD then
  4466. { Don't add size suffix for MOVSXD }
  4467. {$endif x86_64}
  4468. PreMessage := PreMessage + debug_opsize2str(NewSize);
  4469. Inc(taicpu(p).oper[0]^.ref^.offset, NewOffset);
  4470. taicpu(p).opcode := MovUnaligned;
  4471. taicpu(p).opsize := NewSize;
  4472. DebugMsg(SPeepholeOptimization + PreMessage + ' ' +
  4473. debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr/Sar2Movx)', p);
  4474. RemoveInstruction(hp1);
  4475. Result := True;
  4476. Exit;
  4477. end;
  4478. end;
  4479. { Backward optimisation shared with OptPass2MOV }
  4480. if FuncMov2Func(p, hp1) then
  4481. begin
  4482. Result := True;
  4483. Exit;
  4484. end;
  4485. end;
  4486. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  4487. var
  4488. hp1 : tai;
  4489. begin
  4490. Result:=false;
  4491. if taicpu(p).ops <> 2 then
  4492. exit;
  4493. if (MatchOpType(taicpu(p),top_reg,top_reg) and GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg)) or
  4494. GetNextInstruction(p,hp1) then
  4495. begin
  4496. if MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4497. (taicpu(hp1).ops = 2) then
  4498. begin
  4499. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  4500. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  4501. { movXX reg1, mem1 or movXX mem1, reg1
  4502. movXX mem2, reg2 movXX reg2, mem2}
  4503. begin
  4504. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  4505. { movXX reg1, mem1 or movXX mem1, reg1
  4506. movXX mem2, reg1 movXX reg2, mem1}
  4507. begin
  4508. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  4509. begin
  4510. { Removes the second statement from
  4511. movXX reg1, mem1/reg2
  4512. movXX mem1/reg2, reg1
  4513. }
  4514. if taicpu(p).oper[0]^.typ=top_reg then
  4515. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  4516. { Removes the second statement from
  4517. movXX mem1/reg1, reg2
  4518. movXX reg2, mem1/reg1
  4519. }
  4520. if (taicpu(p).oper[1]^.typ=top_reg) and
  4521. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  4522. begin
  4523. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  4524. RemoveInstruction(hp1);
  4525. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  4526. Result:=true;
  4527. exit;
  4528. end
  4529. else if (taicpu(hp1).oper[1]^.typ<>top_ref) or (not(vol_write in taicpu(hp1).oper[1]^.ref^.volatility)) and
  4530. (taicpu(hp1).oper[0]^.typ<>top_ref) or (not(vol_read in taicpu(hp1).oper[0]^.ref^.volatility)) then
  4531. begin
  4532. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  4533. RemoveInstruction(hp1);
  4534. Result:=true;
  4535. exit;
  4536. end;
  4537. end
  4538. end;
  4539. end;
  4540. end;
  4541. end;
  4542. end;
  4543. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  4544. var
  4545. hp1 : tai;
  4546. begin
  4547. result:=false;
  4548. { replace
  4549. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  4550. MovX %mreg2,%mreg1
  4551. dealloc %mreg2
  4552. by
  4553. <Op>X %mreg2,%mreg1
  4554. ?
  4555. }
  4556. if GetNextInstruction(p,hp1) and
  4557. { we mix single and double opperations here because we assume that the compiler
  4558. generates vmovapd only after double operations and vmovaps only after single operations }
  4559. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4560. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4561. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  4562. (taicpu(p).oper[0]^.typ=top_reg) then
  4563. begin
  4564. TransferUsedRegs(TmpUsedRegs);
  4565. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4566. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4567. begin
  4568. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  4569. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4570. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  4571. RemoveInstruction(hp1);
  4572. result:=true;
  4573. end;
  4574. end;
  4575. end;
  4576. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  4577. var
  4578. hp1, p_label, p_dist, hp1_dist: tai;
  4579. JumpLabel, JumpLabel_dist: TAsmLabel;
  4580. FirstValue, SecondValue: TCGInt;
  4581. begin
  4582. Result := False;
  4583. if (taicpu(p).oper[0]^.typ = top_const) and
  4584. (taicpu(p).oper[0]^.val <> -1) then
  4585. begin
  4586. { Convert unsigned maximum constants to -1 to aid optimisation }
  4587. case taicpu(p).opsize of
  4588. S_B:
  4589. if (taicpu(p).oper[0]^.val and $FF) = $FF then
  4590. begin
  4591. taicpu(p).oper[0]^.val := -1;
  4592. Result := True;
  4593. Exit;
  4594. end;
  4595. S_W:
  4596. if (taicpu(p).oper[0]^.val and $FFFF) = $FFFF then
  4597. begin
  4598. taicpu(p).oper[0]^.val := -1;
  4599. Result := True;
  4600. Exit;
  4601. end;
  4602. S_L:
  4603. if (taicpu(p).oper[0]^.val and $FFFFFFFF) = $FFFFFFFF then
  4604. begin
  4605. taicpu(p).oper[0]^.val := -1;
  4606. Result := True;
  4607. Exit;
  4608. end;
  4609. {$ifdef x86_64}
  4610. S_Q:
  4611. { Storing anything greater than $7FFFFFFF is not possible so do
  4612. nothing };
  4613. {$endif x86_64}
  4614. else
  4615. InternalError(2021121001);
  4616. end;
  4617. end;
  4618. if GetNextInstruction(p, hp1) and
  4619. TrySwapMovCmp(p, hp1) then
  4620. begin
  4621. Result := True;
  4622. Exit;
  4623. end;
  4624. { Search for:
  4625. test $x,(reg/ref)
  4626. jne @lbl1
  4627. test $y,(reg/ref) (same register or reference)
  4628. jne @lbl1
  4629. Change to:
  4630. test $(x or y),(reg/ref)
  4631. jne @lbl1
  4632. (Note, this doesn't work with je instead of jne)
  4633. Also catch cases where "cmp $0,(reg/ref)" and "test %reg,%reg" are used.
  4634. Also search for:
  4635. test $x,(reg/ref)
  4636. je @lbl1
  4637. test $y,(reg/ref)
  4638. je/jne @lbl2
  4639. If (x or y) = x, then the second jump is deterministic
  4640. }
  4641. if (
  4642. (
  4643. (taicpu(p).oper[0]^.typ = top_const) or
  4644. (
  4645. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4646. (taicpu(p).oper[0]^.typ = top_reg) and
  4647. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg)
  4648. )
  4649. ) and
  4650. MatchInstruction(hp1, A_JCC, [])
  4651. ) then
  4652. begin
  4653. if (taicpu(p).oper[0]^.typ = top_reg) and
  4654. MatchOperand(taicpu(p).oper[1]^, taicpu(p).oper[0]^.reg) then
  4655. FirstValue := -1
  4656. else
  4657. FirstValue := taicpu(p).oper[0]^.val;
  4658. { If we have several test/jne's in a row, it might be the case that
  4659. the second label doesn't go to the same location, but the one
  4660. after it might (e.g. test; jne @lbl1; test; jne @lbl2; test @lbl1),
  4661. so accommodate for this with a while loop.
  4662. }
  4663. hp1_dist := hp1;
  4664. if GetNextInstruction(hp1, p_dist) and
  4665. (p_dist.typ = ait_instruction) and
  4666. (
  4667. (
  4668. (taicpu(p_dist).opcode = A_TEST) and
  4669. (
  4670. (taicpu(p_dist).oper[0]^.typ = top_const) or
  4671. { test %reg,%reg can be considered equivalent to test, -1,%reg }
  4672. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^)
  4673. )
  4674. ) or
  4675. (
  4676. { cmp 0,%reg = test %reg,%reg }
  4677. (taicpu(p_dist).opcode = A_CMP) and
  4678. MatchOperand(taicpu(p_dist).oper[0]^, 0)
  4679. )
  4680. ) and
  4681. { Make sure the destination operands are actually the same }
  4682. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4683. GetNextInstruction(p_dist, hp1_dist) and
  4684. MatchInstruction(hp1_dist, A_JCC, []) then
  4685. begin
  4686. if
  4687. (taicpu(p_dist).opcode = A_CMP) { constant will be zero } or
  4688. (
  4689. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  4690. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p_dist).oper[0]^.reg)
  4691. ) then
  4692. SecondValue := -1
  4693. else
  4694. SecondValue := taicpu(p_dist).oper[0]^.val;
  4695. { If both of the TEST constants are identical, delete the second
  4696. TEST that is unnecessary. }
  4697. if (FirstValue = SecondValue) then
  4698. begin
  4699. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/TEST; removed superfluous TEST', p_dist);
  4700. RemoveInstruction(p_dist);
  4701. { Don't let the flags register become deallocated and reallocated between the jumps }
  4702. AllocRegBetween(NR_DEFAULTFLAGS, hp1, hp1_dist, UsedRegs);
  4703. Result := True;
  4704. if condition_in(taicpu(hp1_dist).condition, taicpu(hp1).condition) then
  4705. begin
  4706. { Since the second jump's condition is a subset of the first, we
  4707. know it will never branch because the first jump dominates it.
  4708. Get it out of the way now rather than wait for the jump
  4709. optimisations for a speed boost. }
  4710. if IsJumpToLabel(taicpu(hp1_dist)) then
  4711. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4712. DebugMsg(SPeepholeOptimization + 'Removed dominated jump (via TEST/Jcc/TEST)', hp1_dist);
  4713. RemoveInstruction(hp1_dist);
  4714. end
  4715. else if condition_in(inverse_cond(taicpu(hp1).condition), taicpu(hp1_dist).condition) then
  4716. begin
  4717. { If the inverse of the first condition is a subset of the second,
  4718. the second one will definitely branch if the first one doesn't }
  4719. DebugMsg(SPeepholeOptimization + 'Conditional jump will always branch (via TEST/Jcc/TEST)', hp1_dist);
  4720. MakeUnconditional(taicpu(hp1_dist));
  4721. RemoveDeadCodeAfterJump(hp1_dist);
  4722. end;
  4723. Exit;
  4724. end;
  4725. if (taicpu(hp1).condition in [C_NE, C_NZ]) and
  4726. (taicpu(hp1_dist).condition in [C_NE, C_NZ]) and
  4727. { If the first instruction is test %reg,%reg or test $-1,%reg,
  4728. then the second jump will never branch, so it can also be
  4729. removed regardless of where it goes }
  4730. (
  4731. (FirstValue = -1) or
  4732. (SecondValue = -1) or
  4733. MatchOperand(taicpu(hp1_dist).oper[0]^, taicpu(hp1).oper[0]^)
  4734. ) then
  4735. begin
  4736. { Same jump location... can be a register since nothing's changed }
  4737. { If any of the entries are equivalent to test %reg,%reg, then the
  4738. merged $(x or y) is also test %reg,%reg / test $-1,%reg }
  4739. taicpu(p).loadconst(0, FirstValue or SecondValue);
  4740. if IsJumpToLabel(taicpu(hp1_dist)) then
  4741. TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol).DecRefs;
  4742. DebugMsg(SPeepholeOptimization + 'TEST/JNE/TEST/JNE merged', p);
  4743. RemoveInstruction(hp1_dist);
  4744. { Only remove the second test if no jumps or other conditional instructions follow }
  4745. TransferUsedRegs(TmpUsedRegs);
  4746. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  4747. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  4748. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  4749. RemoveInstruction(p_dist);
  4750. Result := True;
  4751. Exit;
  4752. end;
  4753. end;
  4754. end;
  4755. { Search for:
  4756. test %reg,%reg
  4757. j(c1) @lbl1
  4758. ...
  4759. @lbl:
  4760. test %reg,%reg (same register)
  4761. j(c2) @lbl2
  4762. If c2 is a subset of c1, change to:
  4763. test %reg,%reg
  4764. j(c1) @lbl2
  4765. (@lbl1 may become a dead label as a result)
  4766. }
  4767. if (taicpu(p).oper[1]^.typ = top_reg) and
  4768. (taicpu(p).oper[0]^.typ = top_reg) and
  4769. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  4770. MatchInstruction(hp1, A_JCC, []) and
  4771. IsJumpToLabel(taicpu(hp1)) then
  4772. begin
  4773. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  4774. p_label := nil;
  4775. if Assigned(JumpLabel) then
  4776. p_label := getlabelwithsym(JumpLabel);
  4777. if Assigned(p_label) and
  4778. GetNextInstruction(p_label, p_dist) and
  4779. MatchInstruction(p_dist, A_TEST, []) and
  4780. { It's fine if the second test uses smaller sub-registers }
  4781. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  4782. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  4783. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  4784. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  4785. GetNextInstruction(p_dist, hp1_dist) and
  4786. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4787. begin
  4788. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4789. if JumpLabel = JumpLabel_dist then
  4790. { This is an infinite loop }
  4791. Exit;
  4792. { Best optimisation when the first condition is a subset (or equal) of the second }
  4793. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  4794. begin
  4795. { Any registers used here will already be allocated }
  4796. if Assigned(JumpLabel) then
  4797. JumpLabel.DecRefs;
  4798. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  4799. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  4800. Result := True;
  4801. Exit;
  4802. end;
  4803. end;
  4804. end;
  4805. end;
  4806. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  4807. var
  4808. hp1, hp2: tai;
  4809. ActiveReg: TRegister;
  4810. OldOffset: asizeint;
  4811. ThisConst: TCGInt;
  4812. function RegDeallocated: Boolean;
  4813. begin
  4814. TransferUsedRegs(TmpUsedRegs);
  4815. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4816. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  4817. end;
  4818. begin
  4819. result:=false;
  4820. hp1 := nil;
  4821. { replace
  4822. addX const,%reg1
  4823. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  4824. dealloc %reg1
  4825. by
  4826. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  4827. }
  4828. if MatchOpType(taicpu(p),top_const,top_reg) then
  4829. begin
  4830. ActiveReg := taicpu(p).oper[1]^.reg;
  4831. { Ensures the entire register was updated }
  4832. if (taicpu(p).opsize >= S_L) and
  4833. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  4834. MatchInstruction(hp1,A_LEA,[]) and
  4835. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  4836. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  4837. (
  4838. { Cover the case where the register in the reference is also the destination register }
  4839. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  4840. (
  4841. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  4842. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  4843. RegDeallocated
  4844. )
  4845. ) then
  4846. begin
  4847. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  4848. {$push}
  4849. {$R-}{$Q-}
  4850. { Explicitly disable overflow checking for these offset calculation
  4851. as those do not matter for the final result }
  4852. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  4853. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  4854. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  4855. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  4856. {$pop}
  4857. {$ifdef x86_64}
  4858. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  4859. begin
  4860. { Overflow; abort }
  4861. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  4862. end
  4863. else
  4864. {$endif x86_64}
  4865. begin
  4866. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  4867. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  4868. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  4869. RemoveCurrentP(p, hp1)
  4870. else
  4871. RemoveCurrentP(p);
  4872. result:=true;
  4873. Exit;
  4874. end;
  4875. end;
  4876. if (
  4877. { Save calling GetNextInstructionUsingReg again }
  4878. Assigned(hp1) or
  4879. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  4880. ) and
  4881. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  4882. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  4883. begin
  4884. if taicpu(hp1).oper[0]^.typ = top_const then
  4885. begin
  4886. { Merge add const1,%reg; add/sub const2,%reg to add const1+/-const2,%reg }
  4887. if taicpu(hp1).opcode = A_ADD then
  4888. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  4889. else
  4890. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  4891. Result := True;
  4892. { Handle any overflows }
  4893. case taicpu(p).opsize of
  4894. S_B:
  4895. taicpu(p).oper[0]^.val := ThisConst and $FF;
  4896. S_W:
  4897. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  4898. S_L:
  4899. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  4900. {$ifdef x86_64}
  4901. S_Q:
  4902. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  4903. { Overflow; abort }
  4904. Result := False
  4905. else
  4906. taicpu(p).oper[0]^.val := ThisConst;
  4907. {$endif x86_64}
  4908. else
  4909. InternalError(2021102610);
  4910. end;
  4911. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  4912. if Result then
  4913. begin
  4914. if (taicpu(p).oper[0]^.val < 0) and
  4915. (
  4916. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  4917. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  4918. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  4919. ) then
  4920. begin
  4921. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> SUB',p);
  4922. taicpu(p).opcode := A_SUB;
  4923. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  4924. end
  4925. else
  4926. DebugMsg(SPeepholeOptimization + 'ADD; ADD/SUB -> ADD',p);
  4927. RemoveInstruction(hp1);
  4928. end;
  4929. end
  4930. else
  4931. begin
  4932. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  4933. TransferUsedRegs(TmpUsedRegs);
  4934. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4935. hp2 := p;
  4936. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  4937. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  4938. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  4939. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  4940. begin
  4941. { Move the constant addition to after the reg/ref addition to improve optimisation }
  4942. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1a done',p);
  4943. Asml.Remove(p);
  4944. Asml.InsertAfter(p, hp1);
  4945. p := hp1;
  4946. Result := True;
  4947. Exit;
  4948. end;
  4949. end;
  4950. end;
  4951. if DoArithCombineOpt(p) then
  4952. Result:=true;
  4953. end;
  4954. end;
  4955. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  4956. var
  4957. hp1: tai;
  4958. ref: Integer;
  4959. saveref: treference;
  4960. Multiple: TCGInt;
  4961. Adjacent: Boolean;
  4962. begin
  4963. Result:=false;
  4964. { play save and throw an error if LEA uses a seg register prefix,
  4965. this is most likely an error somewhere else }
  4966. if taicpu(p).oper[0]^.ref^.Segment<>NR_NO then
  4967. internalerror(2022022001);
  4968. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  4969. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  4970. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  4971. (
  4972. { do not mess with leas accessing the stack pointer
  4973. unless it's a null operation }
  4974. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  4975. (
  4976. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  4977. (taicpu(p).oper[0]^.ref^.offset = 0)
  4978. )
  4979. ) and
  4980. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  4981. begin
  4982. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  4983. begin
  4984. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  4985. begin
  4986. taicpu(p).opcode := A_MOV;
  4987. taicpu(p).loadreg(0, taicpu(p).oper[0]^.ref^.base);
  4988. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',p);
  4989. end
  4990. else
  4991. begin
  4992. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  4993. RemoveCurrentP(p);
  4994. end;
  4995. Result:=true;
  4996. exit;
  4997. end
  4998. else if (
  4999. { continue to use lea to adjust the stack pointer,
  5000. it is the recommended way, but only if not optimizing for size }
  5001. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  5002. (cs_opt_size in current_settings.optimizerswitches)
  5003. ) and
  5004. { If the flags register is in use, don't change the instruction
  5005. to an ADD otherwise this will scramble the flags. [Kit] }
  5006. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  5007. ConvertLEA(taicpu(p)) then
  5008. begin
  5009. Result:=true;
  5010. exit;
  5011. end;
  5012. end;
  5013. { Don't optimise if the stack or frame pointer is the destination register }
  5014. if (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) or (taicpu(p).oper[1]^.reg=current_procinfo.framepointer) then
  5015. Exit;
  5016. if GetNextInstruction(p,hp1) and
  5017. (hp1.typ=ait_instruction) then
  5018. begin
  5019. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5020. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  5021. MatchOpType(Taicpu(hp1),top_reg,top_reg) then
  5022. begin
  5023. TransferUsedRegs(TmpUsedRegs);
  5024. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5025. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5026. begin
  5027. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  5028. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  5029. RemoveInstruction(hp1);
  5030. result:=true;
  5031. exit;
  5032. end;
  5033. end;
  5034. { changes
  5035. lea <ref1>, reg1
  5036. <op> ...,<ref. with reg1>,...
  5037. to
  5038. <op> ...,<ref1>,... }
  5039. { find a reference which uses reg1 }
  5040. 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
  5041. ref:=0
  5042. 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
  5043. ref:=1
  5044. else
  5045. ref:=-1;
  5046. if (ref<>-1) and
  5047. { reg1 must be either the base or the index }
  5048. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  5049. begin
  5050. { reg1 can be removed from the reference }
  5051. saveref:=taicpu(hp1).oper[ref]^.ref^;
  5052. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  5053. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  5054. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  5055. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  5056. else
  5057. Internalerror(2019111201);
  5058. { check if the can insert all data of the lea into the second instruction }
  5059. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5060. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  5061. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  5062. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  5063. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  5064. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  5065. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  5066. {$ifdef x86_64}
  5067. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  5068. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  5069. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  5070. )
  5071. {$endif x86_64}
  5072. then
  5073. begin
  5074. { reg1 might not used by the second instruction after it is remove from the reference }
  5075. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  5076. begin
  5077. TransferUsedRegs(TmpUsedRegs);
  5078. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5079. { reg1 is not updated so it might not be used afterwards }
  5080. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  5081. begin
  5082. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  5083. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  5084. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5085. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5086. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5087. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  5088. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  5089. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  5090. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  5091. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  5092. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5093. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5094. RemoveCurrentP(p, hp1);
  5095. result:=true;
  5096. exit;
  5097. end
  5098. end;
  5099. end;
  5100. { recover }
  5101. taicpu(hp1).oper[ref]^.ref^:=saveref;
  5102. end;
  5103. Adjacent := RegInInstruction(taicpu(p).oper[1]^.reg, hp1);
  5104. if Adjacent or
  5105. { Check further ahead (up to 2 instructions ahead for -O2) }
  5106. GetNextInstructionUsingReg(hp1,hp1,taicpu(p).oper[1]^.reg) then
  5107. begin
  5108. { Check common LEA/LEA conditions }
  5109. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  5110. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  5111. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  5112. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  5113. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  5114. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  5115. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  5116. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  5117. (
  5118. { If p and hp1 are adjacent, RegModifiedBetween always returns False, so avoid
  5119. calling it (since it calls GetNextInstruction) }
  5120. Adjacent or
  5121. (
  5122. (
  5123. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  5124. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  5125. ) and (
  5126. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  5127. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5128. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  5129. )
  5130. )
  5131. ) then
  5132. begin
  5133. { changes
  5134. lea (regX,scale), reg1
  5135. lea offset(reg1,reg1), reg1
  5136. to
  5137. lea offset(regX,scale*2), reg1
  5138. and
  5139. lea (regX,scale1), reg1
  5140. lea offset(reg1,scale2), reg1
  5141. to
  5142. lea offset(regX,scale1*scale2), reg1
  5143. ... so long as the final scale does not exceed 8
  5144. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  5145. }
  5146. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5147. (taicpu(p).oper[0]^.ref^.offset = 0) and
  5148. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5149. (
  5150. (
  5151. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5152. ) or (
  5153. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5154. (
  5155. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  5156. (
  5157. { RegUsedBetween always returns False if p and hp1 are adjacent }
  5158. Adjacent or
  5159. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  5160. )
  5161. )
  5162. )
  5163. ) and (
  5164. (
  5165. { lea (reg1,scale2), reg1 variant }
  5166. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  5167. (
  5168. (
  5169. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  5170. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  5171. ) or (
  5172. { lea (regX,regX), reg1 variant }
  5173. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  5174. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  5175. )
  5176. )
  5177. ) or (
  5178. { lea (reg1,reg1), reg1 variant }
  5179. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5180. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  5181. )
  5182. ) then
  5183. begin
  5184. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  5185. { Make everything homogeneous to make calculations easier }
  5186. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  5187. begin
  5188. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  5189. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  5190. taicpu(p).oper[0]^.ref^.scalefactor := 2
  5191. else
  5192. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  5193. taicpu(p).oper[0]^.ref^.base := NR_NO;
  5194. end;
  5195. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  5196. begin
  5197. { Just to prevent miscalculations }
  5198. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  5199. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  5200. else
  5201. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  5202. end
  5203. else
  5204. begin
  5205. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  5206. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  5207. end;
  5208. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  5209. RemoveCurrentP(p);
  5210. result:=true;
  5211. exit;
  5212. end
  5213. { changes
  5214. lea offset1(regX), reg1
  5215. lea offset2(reg1), reg1
  5216. to
  5217. lea offset1+offset2(regX), reg1 }
  5218. else if
  5219. (
  5220. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5221. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  5222. ) or (
  5223. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  5224. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  5225. (
  5226. (
  5227. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5228. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  5229. ) or (
  5230. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  5231. (
  5232. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5233. (
  5234. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5235. (
  5236. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  5237. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  5238. )
  5239. )
  5240. )
  5241. )
  5242. )
  5243. ) then
  5244. begin
  5245. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  5246. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  5247. begin
  5248. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  5249. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5250. { if the register is used as index and base, we have to increase for base as well
  5251. and adapt base }
  5252. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  5253. begin
  5254. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5255. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5256. end;
  5257. end
  5258. else
  5259. begin
  5260. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  5261. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  5262. end;
  5263. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  5264. begin
  5265. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  5266. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  5267. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  5268. end;
  5269. RemoveCurrentP(p);
  5270. result:=true;
  5271. exit;
  5272. end;
  5273. end;
  5274. { Change:
  5275. leal/q $x(%reg1),%reg2
  5276. ...
  5277. shll/q $y,%reg2
  5278. To:
  5279. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  5280. }
  5281. if (taicpu(p).oper[0]^.ref^.base<>NR_STACK_POINTER_REG) and { lea (%rsp,scale),reg is not a valid encoding }
  5282. MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  5283. MatchOpType(taicpu(hp1), top_const, top_reg) and
  5284. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5285. (taicpu(hp1).oper[0]^.val <= 3) then
  5286. begin
  5287. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  5288. TransferUsedRegs(TmpUsedRegs);
  5289. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5290. if
  5291. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  5292. (this works even if scalefactor is zero) }
  5293. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  5294. { Ensure offset doesn't go out of bounds }
  5295. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  5296. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  5297. (
  5298. (
  5299. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, taicpu(p).oper[1]^.reg) and
  5300. (
  5301. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  5302. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  5303. (
  5304. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  5305. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  5306. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  5307. )
  5308. )
  5309. ) or (
  5310. (
  5311. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  5312. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  5313. ) and
  5314. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, taicpu(p).oper[1]^.reg)
  5315. )
  5316. ) then
  5317. begin
  5318. repeat
  5319. with taicpu(p).oper[0]^.ref^ do
  5320. begin
  5321. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  5322. if index = base then
  5323. begin
  5324. if Multiple > 4 then
  5325. { Optimisation will no longer work because resultant
  5326. scale factor will exceed 8 }
  5327. Break;
  5328. base := NR_NO;
  5329. scalefactor := 2;
  5330. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  5331. end
  5332. else if (base <> NR_NO) and (base <> NR_INVALID) then
  5333. begin
  5334. { Scale factor only works on the index register }
  5335. index := base;
  5336. base := NR_NO;
  5337. end;
  5338. { For safety }
  5339. if scalefactor <= 1 then
  5340. begin
  5341. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  5342. scalefactor := Multiple;
  5343. end
  5344. else
  5345. begin
  5346. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  5347. scalefactor := scalefactor * Multiple;
  5348. end;
  5349. offset := offset * Multiple;
  5350. end;
  5351. RemoveInstruction(hp1);
  5352. Result := True;
  5353. Exit;
  5354. { This repeat..until loop exists for the benefit of Break }
  5355. until True;
  5356. end;
  5357. end;
  5358. end;
  5359. end;
  5360. end;
  5361. function TX86AsmOptimizer.DoArithCombineOpt(var p: tai): Boolean;
  5362. var
  5363. hp1 : tai;
  5364. SubInstr: Boolean;
  5365. ThisConst: TCGInt;
  5366. const
  5367. OverflowMin: array[S_B..S_Q] of TCGInt = (-128, -32768, -2147483648, -2147483648);
  5368. { Note: 64-bit-sized arithmetic instructions can only take signed 32-bit immediates }
  5369. OverflowMax: array[S_B..S_Q] of TCGInt = ( 255, 65535, $FFFFFFFF, 2147483647);
  5370. begin
  5371. Result := False;
  5372. if taicpu(p).oper[0]^.typ <> top_const then
  5373. { Should have been confirmed before calling }
  5374. InternalError(2021102601);
  5375. SubInstr := (taicpu(p).opcode = A_SUB);
  5376. if GetLastInstruction(p, hp1) and
  5377. (hp1.typ = ait_instruction) and
  5378. (taicpu(hp1).opsize = taicpu(p).opsize) then
  5379. begin
  5380. if not (taicpu(p).opsize in [S_B, S_W, S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) then
  5381. { Bad size }
  5382. InternalError(2022042001);
  5383. case taicpu(hp1).opcode Of
  5384. A_INC:
  5385. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5386. begin
  5387. if SubInstr then
  5388. ThisConst := taicpu(p).oper[0]^.val - 1
  5389. else
  5390. ThisConst := taicpu(p).oper[0]^.val + 1;
  5391. end
  5392. else
  5393. Exit;
  5394. A_DEC:
  5395. if MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  5396. begin
  5397. if SubInstr then
  5398. ThisConst := taicpu(p).oper[0]^.val + 1
  5399. else
  5400. ThisConst := taicpu(p).oper[0]^.val - 1;
  5401. end
  5402. else
  5403. Exit;
  5404. A_SUB:
  5405. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5406. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5407. begin
  5408. if SubInstr then
  5409. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val
  5410. else
  5411. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val;
  5412. end
  5413. else
  5414. Exit;
  5415. A_ADD:
  5416. if (taicpu(hp1).oper[0]^.typ = top_const) and
  5417. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  5418. begin
  5419. if SubInstr then
  5420. ThisConst := taicpu(p).oper[0]^.val - taicpu(hp1).oper[0]^.val
  5421. else
  5422. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5423. end
  5424. else
  5425. Exit;
  5426. else
  5427. Exit;
  5428. end;
  5429. { Check that the values are in range }
  5430. if (ThisConst < OverflowMin[taicpu(p).opsize]) or (ThisConst > OverflowMax[taicpu(p).opsize]) then
  5431. { Overflow; abort }
  5432. Exit;
  5433. if (ThisConst = 0) then
  5434. begin
  5435. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5436. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5437. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' cancel out (NOP)', p);
  5438. RemoveInstruction(hp1);
  5439. hp1 := tai(p.next);
  5440. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  5441. if not GetLastInstruction(hp1, p) then
  5442. p := hp1;
  5443. end
  5444. else
  5445. begin
  5446. if taicpu(hp1).opercnt=1 then
  5447. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5448. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + '; ' +
  5449. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5450. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p)
  5451. else
  5452. DebugMsg(SPeepholeOptimization + 'Arithmetic combine: ' +
  5453. debug_op2str(taicpu(hp1).opcode) + ' $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_operstr(taicpu(hp1).oper[1]^) + '; ' +
  5454. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(taicpu(p).oper[0]^.val) + ',' + debug_operstr(taicpu(p).oper[1]^) + ' -> ' +
  5455. debug_op2str(taicpu(p).opcode) + ' $' + debug_tostr(ThisConst) + ' ' + debug_operstr(taicpu(p).oper[1]^), p);
  5456. RemoveInstruction(hp1);
  5457. taicpu(p).loadconst(0, ThisConst);
  5458. end;
  5459. Result := True;
  5460. end;
  5461. end;
  5462. function TX86AsmOptimizer.DoMovCmpMemOpt(var p : tai; const hp1: tai; UpdateTmpUsedRegs: Boolean) : Boolean;
  5463. begin
  5464. Result := False;
  5465. if UpdateTmpUsedRegs then
  5466. TransferUsedRegs(TmpUsedRegs);
  5467. if MatchOpType(taicpu(p),top_ref,top_reg) and
  5468. { The x86 assemblers have difficulty comparing values against absolute addresses }
  5469. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) and
  5470. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  5471. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  5472. (
  5473. (
  5474. (taicpu(hp1).opcode = A_TEST)
  5475. ) or (
  5476. (taicpu(hp1).opcode = A_CMP) and
  5477. { A sanity check more than anything }
  5478. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  5479. )
  5480. ) then
  5481. begin
  5482. { change
  5483. mov mem, %reg
  5484. cmp/test x, %reg / test %reg,%reg
  5485. (reg deallocated)
  5486. to
  5487. cmp/test x, mem / cmp 0, mem
  5488. }
  5489. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5490. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  5491. begin
  5492. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  5493. if (taicpu(hp1).opcode = A_TEST) and
  5494. (
  5495. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  5496. MatchOperand(taicpu(hp1).oper[0]^, -1)
  5497. ) then
  5498. begin
  5499. taicpu(hp1).opcode := A_CMP;
  5500. taicpu(hp1).loadconst(0, 0);
  5501. end;
  5502. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  5503. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  5504. RemoveCurrentP(p, hp1);
  5505. Result := True;
  5506. Exit;
  5507. end;
  5508. end;
  5509. end;
  5510. function TX86AsmOptimizer.DoSETccLblRETOpt(var p: tai; const hp_label: tai_label) : Boolean;
  5511. var
  5512. hp_allocstart, hp_pos, hp2, hp3, hp4, hp5, hp6: tai;
  5513. ThisReg, SecondReg: TRegister;
  5514. JumpLoc: TAsmLabel;
  5515. NewSize: TOpSize;
  5516. begin
  5517. Result := False;
  5518. {
  5519. Convert:
  5520. j<c> .L1
  5521. .L2:
  5522. mov 1,reg
  5523. jmp .L3 (or ret, although it might not be a RET yet)
  5524. .L1:
  5525. mov 0,reg
  5526. jmp .L3 (or ret)
  5527. ( As long as .L3 <> .L1 or .L2)
  5528. To:
  5529. mov 0,reg
  5530. set<not(c)> reg
  5531. jmp .L3 (or ret)
  5532. .L2:
  5533. mov 1,reg
  5534. jmp .L3 (or ret)
  5535. .L1:
  5536. mov 0,reg
  5537. jmp .L3 (or ret)
  5538. }
  5539. if JumpTargetOp(taicpu(p))^.ref^.refaddr<>addr_full then
  5540. Exit;
  5541. JumpLoc := TAsmLabel(JumpTargetOp(taicpu(p))^.ref^.symbol);
  5542. if GetNextInstruction(hp_label, hp2) and
  5543. MatchInstruction(hp2,A_MOV,[]) and
  5544. (taicpu(hp2).oper[0]^.typ = top_const) and
  5545. (
  5546. (
  5547. (taicpu(hp2).oper[1]^.typ = top_reg)
  5548. {$ifdef i386}
  5549. { Under i386, ESI, EDI, EBP and ESP
  5550. don't have an 8-bit representation }
  5551. and not (getsupreg(taicpu(hp2).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5552. {$endif i386}
  5553. ) or (
  5554. {$ifdef i386}
  5555. (taicpu(hp2).oper[1]^.typ <> top_reg) and
  5556. {$endif i386}
  5557. (taicpu(hp2).opsize = S_B)
  5558. )
  5559. ) and
  5560. GetNextInstruction(hp2, hp3) and
  5561. MatchInstruction(hp3, A_JMP, A_RET, []) and
  5562. (
  5563. (taicpu(hp3).opcode=A_RET) or
  5564. (
  5565. (taicpu(hp3).oper[0]^.ref^.refaddr=addr_full) and
  5566. (tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol)<>tai_label(hp_label).labsym)
  5567. )
  5568. ) and
  5569. GetNextInstruction(hp3, hp4) and
  5570. SkipAligns(hp4, hp4) and
  5571. (hp4.typ=ait_label) and
  5572. (tai_label(hp4).labsym=JumpLoc) and
  5573. (
  5574. not (cs_opt_size in current_settings.optimizerswitches) or
  5575. { If the initial jump is the label's only reference, then it will
  5576. become a dead label if the other conditions are met and hence
  5577. remove at least 2 instructions, including a jump }
  5578. (JumpLoc.getrefs = 1)
  5579. ) and
  5580. { Don't check if hp3 jumps to hp4 because this is a zero-distance jump
  5581. that will be optimised out }
  5582. GetNextInstruction(hp4, hp5) and
  5583. MatchInstruction(hp5,A_MOV,[taicpu(hp2).opsize]) and
  5584. (taicpu(hp5).oper[0]^.typ = top_const) and
  5585. (
  5586. ((taicpu(hp2).oper[0]^.val = 0) and (taicpu(hp5).oper[0]^.val = 1)) or
  5587. ((taicpu(hp2).oper[0]^.val = 1) and (taicpu(hp5).oper[0]^.val = 0))
  5588. ) and
  5589. MatchOperand(taicpu(hp2).oper[1]^,taicpu(hp5).oper[1]^) and
  5590. GetNextInstruction(hp5,hp6) and
  5591. (
  5592. (hp6.typ<>ait_label) or
  5593. SkipLabels(hp6, hp6)
  5594. ) and
  5595. (hp6.typ=ait_instruction) then
  5596. begin
  5597. { First, let's look at the two jumps that are hp3 and hp6 }
  5598. if not
  5599. (
  5600. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5601. (
  5602. (taicpu(hp6).opcode=A_RET) or
  5603. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5604. )
  5605. ) then
  5606. { If condition is False, then the JMP/RET instructions matched conventionally }
  5607. begin
  5608. { See if one of the jumps can be instantly converted into a RET }
  5609. if (taicpu(hp3).opcode=A_JMP) then
  5610. begin
  5611. { Reuse hp5 }
  5612. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol));
  5613. { Make sure hp5 doesn't jump back to .L2 (infinite loop) }
  5614. if not Assigned(hp5) or (hp5=hp4) or not GetNextInstruction(hp5, hp5) then
  5615. Exit;
  5616. if MatchInstruction(hp5, A_RET, []) then
  5617. begin
  5618. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (1st jump)', hp3);
  5619. ConvertJumpToRET(hp3, hp5);
  5620. Result := True;
  5621. end
  5622. else
  5623. Exit;
  5624. end;
  5625. if (taicpu(hp6).opcode=A_JMP) then
  5626. begin
  5627. { Reuse hp5 }
  5628. hp5 := getlabelwithsym(TAsmLabel(JumpTargetOp(taicpu(hp6))^.ref^.symbol));
  5629. if not Assigned(hp5) or not GetNextInstruction(hp5, hp5) then
  5630. Exit;
  5631. if MatchInstruction(hp5, A_RET, []) then
  5632. begin
  5633. DebugMsg(SPeepholeOptimization + 'Converted JMP to RET as part of SETcc optimisation (2nd jump)', hp6);
  5634. ConvertJumpToRET(hp6, hp5);
  5635. Result := True;
  5636. end
  5637. else
  5638. Exit;
  5639. end;
  5640. if not
  5641. (
  5642. (taicpu(hp6).opcode=taicpu(hp3).opcode) and { Both RET or both JMP to the same label }
  5643. (
  5644. (taicpu(hp6).opcode=A_RET) or
  5645. MatchOperand(taicpu(hp6).oper[0]^, taicpu(hp3).oper[0]^)
  5646. )
  5647. ) then
  5648. { Still doesn't match }
  5649. Exit;
  5650. end;
  5651. if (taicpu(hp2).oper[0]^.val = 1) then
  5652. begin
  5653. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5654. DebugMsg(SPeepholeOptimization + 'J(c)Mov1Jmp/RetMov0Jmp/Ret -> Set(~c)Jmp/Ret',p)
  5655. end
  5656. else
  5657. DebugMsg(SPeepholeOptimization + 'J(c)Mov0Jmp/RetMov1Jmp/Ret -> Set(c)Jmp/Ret',p);
  5658. if taicpu(hp2).opsize=S_B then
  5659. begin
  5660. if taicpu(hp2).oper[1]^.typ = top_reg then
  5661. begin
  5662. SecondReg := taicpu(hp2).oper[1]^.reg;
  5663. hp4:=taicpu.op_reg(A_SETcc, S_B, SecondReg);
  5664. end
  5665. else
  5666. begin
  5667. hp4:=taicpu.op_ref(A_SETcc, S_B, taicpu(hp2).oper[1]^.ref^);
  5668. SecondReg := NR_NO;
  5669. end;
  5670. hp_pos := p;
  5671. hp_allocstart := hp4;
  5672. end
  5673. else
  5674. begin
  5675. { Will be a register because the size can't be S_B otherwise }
  5676. SecondReg:=taicpu(hp2).oper[1]^.reg;
  5677. ThisReg:=newreg(R_INTREGISTER,getsupreg(SecondReg), R_SUBL);
  5678. hp4:=taicpu.op_reg(A_SETcc, S_B, ThisReg);
  5679. if (cs_opt_size in current_settings.optimizerswitches) then
  5680. begin
  5681. { Favour using MOVZX when optimising for size }
  5682. case taicpu(hp2).opsize of
  5683. S_W:
  5684. NewSize := S_BW;
  5685. S_L:
  5686. NewSize := S_BL;
  5687. {$ifdef x86_64}
  5688. S_Q:
  5689. begin
  5690. NewSize := S_BL;
  5691. { Will implicitly zero-extend to 64-bit }
  5692. setsubreg(SecondReg, R_SUBD);
  5693. end;
  5694. {$endif x86_64}
  5695. else
  5696. InternalError(2022101301);
  5697. end;
  5698. hp5:=taicpu.op_reg_reg(A_MOVZX, NewSize, ThisReg, SecondReg);
  5699. { Inserting it right before p will guarantee that the flags are also tracked }
  5700. Asml.InsertBefore(hp5, p);
  5701. { Make sure the SET instruction gets inserted before the MOVZX instruction }
  5702. hp_pos := hp5;
  5703. hp_allocstart := hp4;
  5704. end
  5705. else
  5706. begin
  5707. hp5:=taicpu.op_const_reg(A_MOV, taicpu(hp2).opsize, 0, SecondReg);
  5708. { Inserting it right before p will guarantee that the flags are also tracked }
  5709. Asml.InsertBefore(hp5, p);
  5710. hp_pos := p;
  5711. hp_allocstart := hp5;
  5712. end;
  5713. taicpu(hp5).fileinfo:=taicpu(p).fileinfo;
  5714. end;
  5715. taicpu(hp4).fileinfo := taicpu(p).fileinfo;
  5716. taicpu(hp4).condition := taicpu(p).condition;
  5717. asml.InsertBefore(hp4, hp_pos);
  5718. if taicpu(hp3).is_jmp then
  5719. begin
  5720. JumpLoc.decrefs;
  5721. MakeUnconditional(taicpu(p));
  5722. taicpu(p).loadref(0, JumpTargetOp(taicpu(hp3))^.ref^);
  5723. TAsmLabel(JumpTargetOp(taicpu(hp3))^.ref^.symbol).increfs;
  5724. end
  5725. else
  5726. ConvertJumpToRET(p, hp3);
  5727. if SecondReg <> NR_NO then
  5728. { Ensure the destination register is allocated over this region }
  5729. AllocRegBetween(SecondReg, hp_allocstart, p, UsedRegs);
  5730. if (JumpLoc.getrefs = 0) then
  5731. RemoveDeadCodeAfterJump(hp3);
  5732. Result:=true;
  5733. exit;
  5734. end;
  5735. end;
  5736. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  5737. var
  5738. hp1, hp2: tai;
  5739. ActiveReg: TRegister;
  5740. OldOffset: asizeint;
  5741. ThisConst: TCGInt;
  5742. function RegDeallocated: Boolean;
  5743. begin
  5744. TransferUsedRegs(TmpUsedRegs);
  5745. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5746. Result := not(RegUsedAfterInstruction(ActiveReg,hp1,TmpUsedRegs))
  5747. end;
  5748. begin
  5749. Result:=false;
  5750. hp1 := nil;
  5751. { replace
  5752. subX const,%reg1
  5753. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  5754. dealloc %reg1
  5755. by
  5756. leaX -const-const*Y(%reg1,%reg1,Y),%reg2
  5757. }
  5758. if MatchOpType(taicpu(p),top_const,top_reg) then
  5759. begin
  5760. ActiveReg := taicpu(p).oper[1]^.reg;
  5761. { Ensures the entire register was updated }
  5762. if (taicpu(p).opsize >= S_L) and
  5763. GetNextInstructionUsingReg(p,hp1, ActiveReg) and
  5764. MatchInstruction(hp1,A_LEA,[]) and
  5765. (SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.base) or
  5766. SuperRegistersEqual(ActiveReg, taicpu(hp1).oper[0]^.ref^.index)) and
  5767. (
  5768. { Cover the case where the register in the reference is also the destination register }
  5769. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ActiveReg) or
  5770. (
  5771. { Try to avoid the expensive check of RegUsedAfterInstruction if we know it will return False }
  5772. not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ActiveReg) and
  5773. RegDeallocated
  5774. )
  5775. ) then
  5776. begin
  5777. OldOffset := taicpu(hp1).oper[0]^.ref^.offset;
  5778. if ActiveReg=taicpu(hp1).oper[0]^.ref^.base then
  5779. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  5780. if ActiveReg=taicpu(hp1).oper[0]^.ref^.index then
  5781. Dec(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  5782. {$ifdef x86_64}
  5783. if (taicpu(hp1).oper[0]^.ref^.offset > $7FFFFFFF) or (taicpu(hp1).oper[0]^.ref^.offset < -2147483648) then
  5784. begin
  5785. { Overflow; abort }
  5786. taicpu(hp1).oper[0]^.ref^.offset := OldOffset;
  5787. end
  5788. else
  5789. {$endif x86_64}
  5790. begin
  5791. DebugMsg(SPeepholeOptimization + 'SubLea2Lea done',p);
  5792. if not (cs_opt_level3 in current_settings.optimizerswitches) then
  5793. { hp1 is the immediate next instruction for sure - good for a quick speed boost }
  5794. RemoveCurrentP(p, hp1)
  5795. else
  5796. RemoveCurrentP(p);
  5797. result:=true;
  5798. Exit;
  5799. end;
  5800. end;
  5801. if (
  5802. { Save calling GetNextInstructionUsingReg again }
  5803. Assigned(hp1) or
  5804. GetNextInstructionUsingReg(p,hp1, ActiveReg)
  5805. ) and
  5806. MatchInstruction(hp1,A_SUB,[taicpu(p).opsize]) and
  5807. (taicpu(hp1).oper[1]^.reg = ActiveReg) then
  5808. begin
  5809. if taicpu(hp1).oper[0]^.typ = top_const then
  5810. begin
  5811. { Merge add const1,%reg; add const2,%reg to add const1+const2,%reg }
  5812. ThisConst := taicpu(p).oper[0]^.val + taicpu(hp1).oper[0]^.val;
  5813. Result := True;
  5814. { Handle any overflows }
  5815. case taicpu(p).opsize of
  5816. S_B:
  5817. taicpu(p).oper[0]^.val := ThisConst and $FF;
  5818. S_W:
  5819. taicpu(p).oper[0]^.val := ThisConst and $FFFF;
  5820. S_L:
  5821. taicpu(p).oper[0]^.val := ThisConst and $FFFFFFFF;
  5822. {$ifdef x86_64}
  5823. S_Q:
  5824. if (ThisConst > $7FFFFFFF) or (ThisConst < -2147483648) then
  5825. { Overflow; abort }
  5826. Result := False
  5827. else
  5828. taicpu(p).oper[0]^.val := ThisConst;
  5829. {$endif x86_64}
  5830. else
  5831. InternalError(2021102611);
  5832. end;
  5833. { Result may get set to False again if the combined immediate overflows for S_Q sizes }
  5834. if Result then
  5835. begin
  5836. if (taicpu(p).oper[0]^.val < 0) and
  5837. (
  5838. ((taicpu(p).opsize = S_B) and (taicpu(p).oper[0]^.val <> -128)) or
  5839. ((taicpu(p).opsize = S_W) and (taicpu(p).oper[0]^.val <> -32768)) or
  5840. ((taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and (taicpu(p).oper[0]^.val <> -2147483648))
  5841. ) then
  5842. begin
  5843. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> ADD',p);
  5844. taicpu(p).opcode := A_SUB;
  5845. taicpu(p).oper[0]^.val := -taicpu(p).oper[0]^.val;
  5846. end
  5847. else
  5848. DebugMsg(SPeepholeOptimization + 'SUB; ADD/SUB -> SUB',p);
  5849. RemoveInstruction(hp1);
  5850. end;
  5851. end
  5852. else
  5853. begin
  5854. { Make doubly sure the flags aren't in use because the order of subtractions may affect them }
  5855. TransferUsedRegs(TmpUsedRegs);
  5856. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5857. hp2 := p;
  5858. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  5859. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  5860. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  5861. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  5862. begin
  5863. { Move the constant subtraction to after the reg/ref addition to improve optimisation }
  5864. DebugMsg(SPeepholeOptimization + 'Add/sub swap 1b done',p);
  5865. Asml.Remove(p);
  5866. Asml.InsertAfter(p, hp1);
  5867. p := hp1;
  5868. Result := True;
  5869. Exit;
  5870. end;
  5871. end;
  5872. end;
  5873. { * change "subl $2, %esp; pushw x" to "pushl x"}
  5874. { * change "sub/add const1, reg" or "dec reg" followed by
  5875. "sub const2, reg" to one "sub ..., reg" }
  5876. {$ifdef i386}
  5877. if (taicpu(p).oper[0]^.val = 2) and
  5878. (ActiveReg = NR_ESP) and
  5879. { Don't do the sub/push optimization if the sub }
  5880. { comes from setting up the stack frame (JM) }
  5881. (not(GetLastInstruction(p,hp1)) or
  5882. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  5883. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  5884. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  5885. begin
  5886. hp1 := tai(p.next);
  5887. while Assigned(hp1) and
  5888. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  5889. not RegReadByInstruction(NR_ESP,hp1) and
  5890. not RegModifiedByInstruction(NR_ESP,hp1) do
  5891. hp1 := tai(hp1.next);
  5892. if Assigned(hp1) and
  5893. MatchInstruction(hp1,A_PUSH,[S_W]) then
  5894. begin
  5895. taicpu(hp1).changeopsize(S_L);
  5896. if taicpu(hp1).oper[0]^.typ=top_reg then
  5897. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  5898. hp1 := tai(p.next);
  5899. RemoveCurrentp(p, hp1);
  5900. Result:=true;
  5901. exit;
  5902. end;
  5903. end;
  5904. {$endif i386}
  5905. if DoArithCombineOpt(p) then
  5906. Result:=true;
  5907. end;
  5908. end;
  5909. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  5910. var
  5911. TmpBool1,TmpBool2 : Boolean;
  5912. tmpref : treference;
  5913. hp1,hp2: tai;
  5914. mask: tcgint;
  5915. begin
  5916. Result:=false;
  5917. { All these optimisations work on "shl/sal const,%reg" }
  5918. if not MatchOpType(taicpu(p),top_const,top_reg) then
  5919. Exit;
  5920. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  5921. (taicpu(p).oper[0]^.val <= 3) then
  5922. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  5923. begin
  5924. { should we check the next instruction? }
  5925. TmpBool1 := True;
  5926. { have we found an add/sub which could be
  5927. integrated in the lea? }
  5928. TmpBool2 := False;
  5929. reference_reset(tmpref,2,[]);
  5930. TmpRef.index := taicpu(p).oper[1]^.reg;
  5931. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  5932. while TmpBool1 and
  5933. GetNextInstruction(p, hp1) and
  5934. (tai(hp1).typ = ait_instruction) and
  5935. ((((taicpu(hp1).opcode = A_ADD) or
  5936. (taicpu(hp1).opcode = A_SUB)) and
  5937. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  5938. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  5939. (((taicpu(hp1).opcode = A_INC) or
  5940. (taicpu(hp1).opcode = A_DEC)) and
  5941. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5942. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  5943. ((taicpu(hp1).opcode = A_LEA) and
  5944. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  5945. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  5946. (not GetNextInstruction(hp1,hp2) or
  5947. not instrReadsFlags(hp2)) Do
  5948. begin
  5949. TmpBool1 := False;
  5950. if taicpu(hp1).opcode=A_LEA then
  5951. begin
  5952. if (TmpRef.base = NR_NO) and
  5953. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  5954. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  5955. { Segment register isn't a concern here }
  5956. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  5957. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  5958. begin
  5959. TmpBool1 := True;
  5960. TmpBool2 := True;
  5961. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  5962. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  5963. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  5964. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  5965. RemoveInstruction(hp1);
  5966. end
  5967. end
  5968. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  5969. begin
  5970. TmpBool1 := True;
  5971. TmpBool2 := True;
  5972. case taicpu(hp1).opcode of
  5973. A_ADD:
  5974. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5975. A_SUB:
  5976. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  5977. else
  5978. internalerror(2019050536);
  5979. end;
  5980. RemoveInstruction(hp1);
  5981. end
  5982. else
  5983. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  5984. (((taicpu(hp1).opcode = A_ADD) and
  5985. (TmpRef.base = NR_NO)) or
  5986. (taicpu(hp1).opcode = A_INC) or
  5987. (taicpu(hp1).opcode = A_DEC)) then
  5988. begin
  5989. TmpBool1 := True;
  5990. TmpBool2 := True;
  5991. case taicpu(hp1).opcode of
  5992. A_ADD:
  5993. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  5994. A_INC:
  5995. inc(TmpRef.offset);
  5996. A_DEC:
  5997. dec(TmpRef.offset);
  5998. else
  5999. internalerror(2019050535);
  6000. end;
  6001. RemoveInstruction(hp1);
  6002. end;
  6003. end;
  6004. if TmpBool2
  6005. {$ifndef x86_64}
  6006. or
  6007. ((current_settings.optimizecputype < cpu_Pentium2) and
  6008. (taicpu(p).oper[0]^.val <= 3) and
  6009. not(cs_opt_size in current_settings.optimizerswitches))
  6010. {$endif x86_64}
  6011. then
  6012. begin
  6013. if not(TmpBool2) and
  6014. (taicpu(p).oper[0]^.val=1) then
  6015. begin
  6016. taicpu(p).opcode := A_ADD;
  6017. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6018. end
  6019. else
  6020. begin
  6021. taicpu(p).opcode := A_LEA;
  6022. taicpu(p).loadref(0, TmpRef);
  6023. end;
  6024. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  6025. Result := True;
  6026. end;
  6027. end
  6028. {$ifndef x86_64}
  6029. else if (current_settings.optimizecputype < cpu_Pentium2) then
  6030. begin
  6031. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  6032. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  6033. (unlike shl, which is only Tairable in the U pipe) }
  6034. if taicpu(p).oper[0]^.val=1 then
  6035. begin
  6036. taicpu(p).opcode := A_ADD;
  6037. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  6038. Result := True;
  6039. end
  6040. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  6041. "shl $3, %reg" to "lea (,%reg,8), %reg }
  6042. else if (taicpu(p).opsize = S_L) and
  6043. (taicpu(p).oper[0]^.val<= 3) then
  6044. begin
  6045. reference_reset(tmpref,2,[]);
  6046. TmpRef.index := taicpu(p).oper[1]^.reg;
  6047. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  6048. taicpu(p).opcode := A_LEA;
  6049. taicpu(p).loadref(0, TmpRef);
  6050. Result := True;
  6051. end;
  6052. end
  6053. {$endif x86_64}
  6054. else if
  6055. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  6056. (
  6057. (
  6058. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  6059. SetAndTest(hp1, hp2)
  6060. {$ifdef x86_64}
  6061. ) or
  6062. (
  6063. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  6064. GetNextInstruction(hp1, hp2) and
  6065. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  6066. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6067. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  6068. {$endif x86_64}
  6069. )
  6070. ) and
  6071. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  6072. begin
  6073. { Change:
  6074. shl x, %reg1
  6075. mov -(1<<x), %reg2
  6076. and %reg2, %reg1
  6077. Or:
  6078. shl x, %reg1
  6079. and -(1<<x), %reg1
  6080. To just:
  6081. shl x, %reg1
  6082. Since the and operation only zeroes bits that are already zero from the shl operation
  6083. }
  6084. case taicpu(p).oper[0]^.val of
  6085. 8:
  6086. mask:=$FFFFFFFFFFFFFF00;
  6087. 16:
  6088. mask:=$FFFFFFFFFFFF0000;
  6089. 32:
  6090. mask:=$FFFFFFFF00000000;
  6091. 63:
  6092. { Constant pre-calculated to prevent overflow errors with Int64 }
  6093. mask:=$8000000000000000;
  6094. else
  6095. begin
  6096. if taicpu(p).oper[0]^.val >= 64 then
  6097. { Shouldn't happen realistically, since the register
  6098. is guaranteed to be set to zero at this point }
  6099. mask := 0
  6100. else
  6101. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  6102. end;
  6103. end;
  6104. if taicpu(hp1).oper[0]^.val = mask then
  6105. begin
  6106. { Everything checks out, perform the optimisation, as long as
  6107. the FLAGS register isn't being used}
  6108. TransferUsedRegs(TmpUsedRegs);
  6109. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6110. {$ifdef x86_64}
  6111. if (hp1 <> hp2) then
  6112. begin
  6113. { "shl/mov/and" version }
  6114. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6115. { Don't do the optimisation if the FLAGS register is in use }
  6116. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  6117. begin
  6118. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  6119. { Don't remove the 'mov' instruction if its register is used elsewhere }
  6120. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  6121. begin
  6122. RemoveInstruction(hp1);
  6123. Result := True;
  6124. end;
  6125. { Only set Result to True if the 'mov' instruction was removed }
  6126. RemoveInstruction(hp2);
  6127. end;
  6128. end
  6129. else
  6130. {$endif x86_64}
  6131. begin
  6132. { "shl/and" version }
  6133. { Don't do the optimisation if the FLAGS register is in use }
  6134. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  6135. begin
  6136. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  6137. RemoveInstruction(hp1);
  6138. Result := True;
  6139. end;
  6140. end;
  6141. Exit;
  6142. end
  6143. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  6144. begin
  6145. { Even if the mask doesn't allow for its removal, we might be
  6146. able to optimise the mask for the "shl/and" version, which
  6147. may permit other peephole optimisations }
  6148. {$ifdef DEBUG_AOPTCPU}
  6149. mask := taicpu(hp1).oper[0]^.val and mask;
  6150. if taicpu(hp1).oper[0]^.val <> mask then
  6151. begin
  6152. DebugMsg(
  6153. SPeepholeOptimization +
  6154. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  6155. ' to $' + debug_tostr(mask) +
  6156. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  6157. taicpu(hp1).oper[0]^.val := mask;
  6158. end;
  6159. {$else DEBUG_AOPTCPU}
  6160. { If debugging is off, just set the operand even if it's the same }
  6161. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  6162. {$endif DEBUG_AOPTCPU}
  6163. end;
  6164. end;
  6165. {
  6166. change
  6167. shl/sal const,reg
  6168. <op> ...(...,reg,1),...
  6169. into
  6170. <op> ...(...,reg,1 shl const),...
  6171. if const in 1..3
  6172. }
  6173. if MatchOpType(taicpu(p), top_const, top_reg) and
  6174. (taicpu(p).oper[0]^.val in [1..3]) and
  6175. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) and
  6176. ((MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  6177. MatchOpType(taicpu(hp1),top_ref,top_reg)) or
  6178. (MatchInstruction(hp1,A_FST,A_FSTP,A_FLD,[]) and
  6179. MatchOpType(taicpu(hp1),top_ref))
  6180. ) and
  6181. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  6182. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  6183. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  6184. begin
  6185. TransferUsedRegs(TmpUsedRegs);
  6186. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6187. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  6188. begin
  6189. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  6190. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  6191. RemoveCurrentP(p);
  6192. Result:=true;
  6193. end;
  6194. end;
  6195. end;
  6196. class function TX86AsmOptimizer.IsShrMovZFoldable(shr_size, movz_size: topsize; Shift: TCGInt): Boolean;
  6197. begin
  6198. case shr_size of
  6199. S_B:
  6200. { No valid combinations }
  6201. Result := False;
  6202. S_W:
  6203. Result := (Shift >= 8) and (movz_size = S_BW);
  6204. S_L:
  6205. Result :=
  6206. (Shift >= 24) { Any opsize is valid for this shift } or
  6207. ((Shift >= 16) and (movz_size = S_WL));
  6208. {$ifdef x86_64}
  6209. S_Q:
  6210. Result :=
  6211. (Shift >= 56) { Any opsize is valid for this shift } or
  6212. ((Shift >= 48) and (movz_size = S_WL));
  6213. {$endif x86_64}
  6214. else
  6215. InternalError(2022081510);
  6216. end;
  6217. end;
  6218. function TX86AsmOptimizer.OptPass1SHR(var p : tai) : boolean;
  6219. var
  6220. hp1, hp2: tai;
  6221. Shift: TCGInt;
  6222. LimitSize: Topsize;
  6223. DoNotMerge: Boolean;
  6224. begin
  6225. Result := False;
  6226. { All these optimisations work on "shr const,%reg" }
  6227. if not MatchOpType(taicpu(p), top_const, top_reg) then
  6228. Exit;
  6229. DoNotMerge := False;
  6230. Shift := taicpu(p).oper[0]^.val;
  6231. LimitSize := taicpu(p).opsize;
  6232. hp1 := p;
  6233. repeat
  6234. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  6235. Exit;
  6236. case taicpu(hp1).opcode of
  6237. A_TEST, A_CMP, A_Jcc:
  6238. { Skip over conditional jumps and relevant comparisons }
  6239. Continue;
  6240. A_MOVZX:
  6241. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  6242. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  6243. begin
  6244. { Since the original register is being read as is, subsequent
  6245. SHRs must not be merged at this point }
  6246. DoNotMerge := True;
  6247. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  6248. begin
  6249. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then { Different register target }
  6250. begin
  6251. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 1)', hp1);
  6252. taicpu(hp1).opcode := A_MOV;
  6253. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  6254. case taicpu(hp1).opsize of
  6255. S_BW:
  6256. taicpu(hp1).opsize := S_W;
  6257. S_BL, S_WL:
  6258. taicpu(hp1).opsize := S_L;
  6259. else
  6260. InternalError(2022081503);
  6261. end;
  6262. { p itself hasn't changed, so no need to set Result to True }
  6263. Include(OptsToCheck, aoc_ForceNewIteration);
  6264. { See if there's anything afterwards that can be
  6265. optimised, since the input register hasn't changed }
  6266. Continue;
  6267. end;
  6268. { NOTE: If the MOVZX instruction reads and writes the same
  6269. register, defer this to the post-peephole optimisation stage }
  6270. Exit;
  6271. end;
  6272. end;
  6273. A_SHL, A_SAL, A_SHR:
  6274. if (taicpu(hp1).opsize <= LimitSize) and
  6275. MatchOpType(taicpu(hp1), top_const, top_reg) and
  6276. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  6277. begin
  6278. { Make sure the sizes don't exceed the register size limit
  6279. (measured by the shift value falling below the limit) }
  6280. if taicpu(hp1).opsize < LimitSize then
  6281. LimitSize := taicpu(hp1).opsize;
  6282. if taicpu(hp1).opcode = A_SHR then
  6283. Inc(Shift, taicpu(hp1).oper[0]^.val)
  6284. else
  6285. begin
  6286. Dec(Shift, taicpu(hp1).oper[0]^.val);
  6287. DoNotMerge := True;
  6288. end;
  6289. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  6290. Exit;
  6291. { Since we've established that the combined shift is within
  6292. limits, we can actually combine the adjacent SHR
  6293. instructions even if they're different sizes }
  6294. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  6295. begin
  6296. hp2 := tai(hp1.Previous);
  6297. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 1', p);
  6298. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  6299. RemoveInstruction(hp1);
  6300. hp1 := hp2;
  6301. { Though p has changed, only the constant has, and its
  6302. effects can still be detected on the next iteration of
  6303. the repeat..until loop }
  6304. Include(OptsToCheck, aoc_ForceNewIteration);
  6305. end;
  6306. { Move onto the next instruction }
  6307. Continue;
  6308. end;
  6309. else
  6310. ;
  6311. end;
  6312. Break;
  6313. until False;
  6314. end;
  6315. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  6316. var
  6317. CurrentRef: TReference;
  6318. FullReg: TRegister;
  6319. hp1, hp2: tai;
  6320. begin
  6321. Result := False;
  6322. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  6323. Exit;
  6324. { We assume you've checked if the operand is actually a reference by
  6325. this point. If it isn't, you'll most likely get an access violation }
  6326. CurrentRef := first_mov.oper[1]^.ref^;
  6327. { Memory must be aligned }
  6328. if (CurrentRef.offset mod 4) <> 0 then
  6329. Exit;
  6330. Inc(CurrentRef.offset);
  6331. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6332. if MatchOperand(second_mov.oper[0]^, 0) and
  6333. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  6334. GetNextInstruction(second_mov, hp1) and
  6335. (hp1.typ = ait_instruction) and
  6336. (taicpu(hp1).opcode = A_MOV) and
  6337. MatchOpType(taicpu(hp1), top_const, top_ref) and
  6338. (taicpu(hp1).oper[0]^.val = 0) then
  6339. begin
  6340. Inc(CurrentRef.offset);
  6341. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  6342. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  6343. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  6344. begin
  6345. case taicpu(hp1).opsize of
  6346. S_B:
  6347. if GetNextInstruction(hp1, hp2) and
  6348. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  6349. MatchOpType(taicpu(hp2), top_const, top_ref) and
  6350. (taicpu(hp2).oper[0]^.val = 0) then
  6351. begin
  6352. Inc(CurrentRef.offset);
  6353. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  6354. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  6355. (taicpu(hp2).opsize = S_B) then
  6356. begin
  6357. RemoveInstruction(hp1);
  6358. RemoveInstruction(hp2);
  6359. first_mov.opsize := S_L;
  6360. if first_mov.oper[0]^.typ = top_reg then
  6361. begin
  6362. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  6363. { Reuse second_mov as a MOVZX instruction }
  6364. second_mov.opcode := A_MOVZX;
  6365. second_mov.opsize := S_BL;
  6366. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6367. second_mov.loadreg(1, FullReg);
  6368. first_mov.oper[0]^.reg := FullReg;
  6369. asml.Remove(second_mov);
  6370. asml.InsertBefore(second_mov, first_mov);
  6371. end
  6372. else
  6373. { It's a value }
  6374. begin
  6375. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  6376. RemoveInstruction(second_mov);
  6377. end;
  6378. Result := True;
  6379. Exit;
  6380. end;
  6381. end;
  6382. S_W:
  6383. begin
  6384. RemoveInstruction(hp1);
  6385. first_mov.opsize := S_L;
  6386. if first_mov.oper[0]^.typ = top_reg then
  6387. begin
  6388. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  6389. { Reuse second_mov as a MOVZX instruction }
  6390. second_mov.opcode := A_MOVZX;
  6391. second_mov.opsize := S_BL;
  6392. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  6393. second_mov.loadreg(1, FullReg);
  6394. first_mov.oper[0]^.reg := FullReg;
  6395. asml.Remove(second_mov);
  6396. asml.InsertBefore(second_mov, first_mov);
  6397. end
  6398. else
  6399. { It's a value }
  6400. begin
  6401. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  6402. RemoveInstruction(second_mov);
  6403. end;
  6404. Result := True;
  6405. Exit;
  6406. end;
  6407. else
  6408. ;
  6409. end;
  6410. end;
  6411. end;
  6412. end;
  6413. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  6414. { returns true if a "continue" should be done after this optimization }
  6415. var
  6416. hp1, hp2: tai;
  6417. begin
  6418. Result := false;
  6419. if MatchOpType(taicpu(p),top_ref) and
  6420. GetNextInstruction(p, hp1) and
  6421. (hp1.typ = ait_instruction) and
  6422. (((taicpu(hp1).opcode = A_FLD) and
  6423. (taicpu(p).opcode = A_FSTP)) or
  6424. ((taicpu(p).opcode = A_FISTP) and
  6425. (taicpu(hp1).opcode = A_FILD))) and
  6426. MatchOpType(taicpu(hp1),top_ref) and
  6427. (taicpu(hp1).opsize = taicpu(p).opsize) and
  6428. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6429. begin
  6430. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  6431. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  6432. GetNextInstruction(hp1, hp2) and
  6433. (((hp2.typ = ait_instruction) and
  6434. IsExitCode(hp2) and
  6435. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6436. not(assigned(current_procinfo.procdef.funcretsym) and
  6437. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  6438. (taicpu(p).oper[0]^.ref^.index = NR_NO)) or
  6439. { fstp <temp>
  6440. fld <temp>
  6441. <dealloc> <temp>
  6442. }
  6443. (SetAndTest(tai(hp1.next),hp2) and (hp2.typ = ait_tempalloc) and
  6444. (tai_tempalloc(hp2).allocation=false) and
  6445. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  6446. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  6447. (tai_tempalloc(hp2).temppos=taicpu(p).oper[0]^.ref^.offset) and
  6448. (((taicpu(p).opsize=S_FX) and (tai_tempalloc(hp2).tempsize=16)) or
  6449. ((taicpu(p).opsize in [S_IQ,S_FL]) and (tai_tempalloc(hp2).tempsize=8)) or
  6450. ((taicpu(p).opsize=S_FS) and (tai_tempalloc(hp2).tempsize=4))
  6451. )
  6452. )
  6453. ) then
  6454. begin
  6455. DebugMsg(SPeepholeOptimization + 'FstpFld2<Nop>',p);
  6456. RemoveInstruction(hp1);
  6457. RemoveCurrentP(p, hp2);
  6458. { first case: exit code }
  6459. if hp2.typ = ait_instruction then
  6460. RemoveLastDeallocForFuncRes(p);
  6461. Result := true;
  6462. end
  6463. else
  6464. { we can do this only in fast math mode as fstp is rounding ...
  6465. ... still disabled as it breaks the compiler and/or rtl }
  6466. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  6467. { ... or if another fstp equal to the first one follows }
  6468. (GetNextInstruction(hp1,hp2) and
  6469. (hp2.typ = ait_instruction) and
  6470. (taicpu(p).opcode=taicpu(hp2).opcode) and
  6471. (taicpu(p).opsize=taicpu(hp2).opsize))
  6472. ) and
  6473. { fst can't store an extended/comp value }
  6474. (taicpu(p).opsize <> S_FX) and
  6475. (taicpu(p).opsize <> S_IQ) then
  6476. begin
  6477. if (taicpu(p).opcode = A_FSTP) then
  6478. taicpu(p).opcode := A_FST
  6479. else
  6480. taicpu(p).opcode := A_FIST;
  6481. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  6482. RemoveInstruction(hp1);
  6483. end;
  6484. end;
  6485. end;
  6486. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  6487. var
  6488. hp1, hp2: tai;
  6489. begin
  6490. result:=false;
  6491. if MatchOpType(taicpu(p),top_reg) and
  6492. GetNextInstruction(p, hp1) and
  6493. (hp1.typ = Ait_Instruction) and
  6494. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6495. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  6496. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  6497. { change to
  6498. fld reg fxxx reg,st
  6499. fxxxp st, st1 (hp1)
  6500. Remark: non commutative operations must be reversed!
  6501. }
  6502. begin
  6503. case taicpu(hp1).opcode Of
  6504. A_FMULP,A_FADDP,
  6505. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6506. begin
  6507. case taicpu(hp1).opcode Of
  6508. A_FADDP: taicpu(hp1).opcode := A_FADD;
  6509. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  6510. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  6511. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  6512. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  6513. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  6514. else
  6515. internalerror(2019050534);
  6516. end;
  6517. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  6518. taicpu(hp1).oper[1]^.reg := NR_ST;
  6519. DebugMsg(SPeepholeOptimization + 'FldF*p2F*',hp1);
  6520. RemoveCurrentP(p, hp1);
  6521. Result:=true;
  6522. exit;
  6523. end;
  6524. else
  6525. ;
  6526. end;
  6527. end
  6528. else
  6529. if MatchOpType(taicpu(p),top_ref) and
  6530. GetNextInstruction(p, hp2) and
  6531. (hp2.typ = Ait_Instruction) and
  6532. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  6533. (taicpu(p).opsize in [S_FS, S_FL]) and
  6534. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  6535. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  6536. if GetLastInstruction(p, hp1) and
  6537. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  6538. MatchOpType(taicpu(hp1),top_ref) and
  6539. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  6540. if ((taicpu(hp2).opcode = A_FMULP) or
  6541. (taicpu(hp2).opcode = A_FADDP)) then
  6542. { change to
  6543. fld/fst mem1 (hp1) fld/fst mem1
  6544. fld mem1 (p) fadd/
  6545. faddp/ fmul st, st
  6546. fmulp st, st1 (hp2) }
  6547. begin
  6548. DebugMsg(SPeepholeOptimization + 'Fld/FstFldFaddp/Fmulp2Fld/FstFadd/Fmul',hp1);
  6549. RemoveCurrentP(p, hp1);
  6550. if (taicpu(hp2).opcode = A_FADDP) then
  6551. taicpu(hp2).opcode := A_FADD
  6552. else
  6553. taicpu(hp2).opcode := A_FMUL;
  6554. taicpu(hp2).oper[1]^.reg := NR_ST;
  6555. end
  6556. else
  6557. { change to
  6558. fld/fst mem1 (hp1) fld/fst mem1
  6559. fld mem1 (p) fld st
  6560. }
  6561. begin
  6562. DebugMsg(SPeepholeOptimization + 'Fld/Fst<mem>Fld<mem>2Fld/Fst<mem>Fld<reg>',hp1);
  6563. taicpu(p).changeopsize(S_FL);
  6564. taicpu(p).loadreg(0,NR_ST);
  6565. end
  6566. else
  6567. begin
  6568. case taicpu(hp2).opcode Of
  6569. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  6570. { change to
  6571. fld/fst mem1 (hp1) fld/fst mem1
  6572. fld mem2 (p) fxxx mem2
  6573. fxxxp st, st1 (hp2) }
  6574. begin
  6575. case taicpu(hp2).opcode Of
  6576. A_FADDP: taicpu(p).opcode := A_FADD;
  6577. A_FMULP: taicpu(p).opcode := A_FMUL;
  6578. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  6579. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  6580. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  6581. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  6582. else
  6583. internalerror(2019050533);
  6584. end;
  6585. DebugMsg(SPeepholeOptimization + 'Fld/FstFldF*2Fld/FstF*',p);
  6586. RemoveInstruction(hp2);
  6587. end
  6588. else
  6589. ;
  6590. end
  6591. end
  6592. end;
  6593. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  6594. begin
  6595. Result := condition_in(cond1, cond2) or
  6596. { Not strictly subsets due to the actual flags checked, but because we're
  6597. comparing integers, E is a subset of AE and GE and their aliases }
  6598. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  6599. end;
  6600. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  6601. var
  6602. v: TCGInt;
  6603. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  6604. FirstMatch: Boolean;
  6605. NewReg: TRegister;
  6606. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  6607. begin
  6608. Result:=false;
  6609. { All these optimisations need a next instruction }
  6610. if not GetNextInstruction(p, hp1) then
  6611. Exit;
  6612. { Search for:
  6613. cmp ###,###
  6614. j(c1) @lbl1
  6615. ...
  6616. @lbl:
  6617. cmp ###,### (same comparison as above)
  6618. j(c2) @lbl2
  6619. If c1 is a subset of c2, change to:
  6620. cmp ###,###
  6621. j(c1) @lbl2
  6622. (@lbl1 may become a dead label as a result)
  6623. }
  6624. { Also handle cases where there are multiple jumps in a row }
  6625. p_jump := hp1;
  6626. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  6627. begin
  6628. if IsJumpToLabel(taicpu(p_jump)) then
  6629. begin
  6630. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  6631. p_label := nil;
  6632. if Assigned(JumpLabel) then
  6633. p_label := getlabelwithsym(JumpLabel);
  6634. if Assigned(p_label) and
  6635. GetNextInstruction(p_label, p_dist) and
  6636. MatchInstruction(p_dist, A_CMP, []) and
  6637. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  6638. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  6639. GetNextInstruction(p_dist, hp1_dist) and
  6640. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  6641. begin
  6642. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  6643. if JumpLabel = JumpLabel_dist then
  6644. { This is an infinite loop }
  6645. Exit;
  6646. { Best optimisation when the first condition is a subset (or equal) of the second }
  6647. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  6648. begin
  6649. { Any registers used here will already be allocated }
  6650. if Assigned(JumpLabel) then
  6651. JumpLabel.DecRefs;
  6652. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  6653. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^); { This also increases the reference count }
  6654. Result := True;
  6655. { Don't exit yet. Since p and p_jump haven't actually been
  6656. removed, we can check for more on this iteration }
  6657. end
  6658. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  6659. GetNextInstruction(hp1_dist, hp1_label) and
  6660. SkipAligns(hp1_label, hp1_label) and
  6661. (hp1_label.typ = ait_label) then
  6662. begin
  6663. JumpLabel_far := tai_label(hp1_label).labsym;
  6664. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  6665. { This is an infinite loop }
  6666. Exit;
  6667. if Assigned(JumpLabel_far) then
  6668. begin
  6669. { In this situation, if the first jump branches, the second one will never,
  6670. branch so change the destination label to after the second jump }
  6671. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  6672. if Assigned(JumpLabel) then
  6673. JumpLabel.DecRefs;
  6674. JumpLabel_far.IncRefs;
  6675. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  6676. Result := True;
  6677. { Don't exit yet. Since p and p_jump haven't actually been
  6678. removed, we can check for more on this iteration }
  6679. Continue;
  6680. end;
  6681. end;
  6682. end;
  6683. end;
  6684. { Search for:
  6685. cmp ###,###
  6686. j(c1) @lbl1
  6687. cmp ###,### (same as first)
  6688. Remove second cmp
  6689. }
  6690. if GetNextInstruction(p_jump, hp2) and
  6691. (
  6692. (
  6693. MatchInstruction(hp2, A_CMP, [taicpu(p).opsize]) and
  6694. (
  6695. (
  6696. MatchOpType(taicpu(p), top_const, top_reg) and
  6697. MatchOpType(taicpu(hp2), top_const, top_reg) and
  6698. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  6699. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6700. ) or (
  6701. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  6702. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  6703. )
  6704. )
  6705. ) or (
  6706. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  6707. MatchOperand(taicpu(p).oper[0]^, 0) and
  6708. (taicpu(p).oper[1]^.typ = top_reg) and
  6709. MatchInstruction(hp2, A_TEST, []) and
  6710. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  6711. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  6712. Reg1WriteOverwritesReg2Entirely(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  6713. )
  6714. ) then
  6715. begin
  6716. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  6717. RemoveInstruction(hp2);
  6718. Result := True;
  6719. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  6720. end;
  6721. GetNextInstruction(p_jump, p_jump);
  6722. end;
  6723. {
  6724. Try to optimise the following:
  6725. cmp $x,### ($x and $y can be registers or constants)
  6726. je @lbl1 (only reference)
  6727. cmp $y,### (### are identical)
  6728. @Lbl:
  6729. sete %reg1
  6730. Change to:
  6731. cmp $x,###
  6732. sete %reg2 (allocate new %reg2)
  6733. cmp $y,###
  6734. sete %reg1
  6735. orb %reg2,%reg1
  6736. (dealloc %reg2)
  6737. This adds an instruction (so don't perform under -Os), but it removes
  6738. a conditional branch.
  6739. }
  6740. if not (cs_opt_size in current_settings.optimizerswitches) and
  6741. (
  6742. (hp1 = p_jump) or
  6743. GetNextInstruction(p, hp1)
  6744. ) and
  6745. MatchInstruction(hp1, A_Jcc, []) and
  6746. IsJumpToLabel(taicpu(hp1)) and
  6747. (taicpu(hp1).condition in [C_E, C_Z]) and
  6748. GetNextInstruction(hp1, hp2) and
  6749. MatchInstruction(hp2, A_CMP, A_TEST, [taicpu(p).opsize]) and
  6750. MatchOperand(taicpu(p).oper[1]^, taicpu(hp2).oper[1]^) and
  6751. { The first operand of CMP instructions can only be a register or
  6752. immediate anyway, so no need to check }
  6753. GetNextInstruction(hp2, p_label) and
  6754. (
  6755. (p_label.typ = ait_label) or
  6756. (
  6757. { Sometimes there's a zero-distance jump before the label, so deal with it here
  6758. to potentially cut down on the iterations of Pass 1 }
  6759. MatchInstruction(p_label, A_Jcc, []) and
  6760. IsJumpToLabel(taicpu(p_label)) and
  6761. { Use p_dist to hold the jump briefly }
  6762. SetAndTest(p_label, p_dist) and
  6763. GetNextInstruction(p_dist, p_label) and
  6764. (p_label.typ = ait_label) and
  6765. (tai_label(p_label).labsym.getrefs >= 2) and
  6766. (JumpTargetOp(taicpu(p_dist))^.ref^.symbol = tai_label(p_label).labsym) and
  6767. { We might as well collapse the jump now }
  6768. CollapseZeroDistJump(p_dist, tai_label(p_label).labsym)
  6769. )
  6770. ) and
  6771. (tai_label(p_label).labsym.getrefs = 1) and
  6772. (JumpTargetOp(taicpu(hp1))^.ref^.symbol = tai_label(p_label).labsym) and
  6773. GetNextInstruction(p_label, p_dist) and
  6774. MatchInstruction(p_dist, A_SETcc, []) and
  6775. (taicpu(p_dist).condition in [C_E, C_Z]) and
  6776. (taicpu(p_dist).oper[0]^.typ = top_reg) and
  6777. { Get the instruction after the SETcc instruction so we can
  6778. allocate a new register over the entire range }
  6779. GetNextInstruction(p_dist, hp1_dist) then
  6780. begin
  6781. TransferUsedRegs(TmpUsedRegs);
  6782. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  6783. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  6784. UpdateUsedRegs(TmpUsedRegs, tai(p_label.Next));
  6785. // UpdateUsedRegs(TmpUsedRegs, tai(p_dist.Next));
  6786. { RegUsedAfterInstruction modifies TmpUsedRegs }
  6787. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, p_dist, TmpUsedRegs) then
  6788. begin
  6789. { Register can appear in p if it's not used afterwards, so only
  6790. allocate between hp1 and hp1_dist }
  6791. NewReg := GetIntRegisterBetween(R_SUBL, TmpUsedRegs, hp1, p_dist);
  6792. if NewReg <> NR_NO then
  6793. begin
  6794. DebugMsg(SPeepholeOptimization + 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR, removing conditional branch', p);
  6795. { Change the jump instruction into a SETcc instruction }
  6796. taicpu(hp1).opcode := A_SETcc;
  6797. taicpu(hp1).opsize := S_B;
  6798. taicpu(hp1).loadreg(0, NewReg);
  6799. { This is now a dead label }
  6800. tai_label(p_label).labsym.decrefs;
  6801. { Prefer adding before the next instruction so the FLAGS
  6802. register is deallocated first }
  6803. hp2 := taicpu.op_reg_reg(A_OR, S_B, NewReg, taicpu(p_dist).oper[0]^.reg);
  6804. taicpu(hp2).fileinfo := taicpu(p_dist).fileinfo;
  6805. AsmL.InsertBefore(
  6806. hp2,
  6807. hp1_dist
  6808. );
  6809. { Make sure the new register is in use over the new instruction
  6810. (long-winded, but things work best when the FLAGS register
  6811. is not allocated here) }
  6812. AllocRegBetween(NewReg, p_dist, hp2, TmpUsedRegs);
  6813. Result := True;
  6814. { Don't exit yet, as p wasn't changed and hp1, while
  6815. modified, is still intact and might be optimised by the
  6816. SETcc optimisation below }
  6817. end;
  6818. end;
  6819. end;
  6820. if taicpu(p).oper[0]^.typ = top_const then
  6821. begin
  6822. if (taicpu(p).oper[0]^.val = 0) and
  6823. (taicpu(p).oper[1]^.typ = top_reg) and
  6824. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  6825. begin
  6826. hp2 := p;
  6827. FirstMatch := True;
  6828. { When dealing with "cmp $0,%reg", only ZF and SF contain
  6829. anything meaningful once it's converted to "test %reg,%reg";
  6830. additionally, some jumps will always (or never) branch, so
  6831. evaluate every jump immediately following the
  6832. comparison, optimising the conditions if possible.
  6833. Similarly with SETcc... those that are always set to 0 or 1
  6834. are changed to MOV instructions }
  6835. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  6836. (
  6837. GetNextInstruction(hp2, hp1) and
  6838. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  6839. ) do
  6840. begin
  6841. FirstMatch := False;
  6842. case taicpu(hp1).condition of
  6843. C_B, C_C, C_NAE, C_O:
  6844. { For B/NAE:
  6845. Will never branch since an unsigned integer can never be below zero
  6846. For C/O:
  6847. Result cannot overflow because 0 is being subtracted
  6848. }
  6849. begin
  6850. if taicpu(hp1).opcode = A_Jcc then
  6851. begin
  6852. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  6853. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  6854. RemoveInstruction(hp1);
  6855. { Since hp1 was deleted, hp2 must not be updated }
  6856. Continue;
  6857. end
  6858. else
  6859. begin
  6860. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  6861. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  6862. taicpu(hp1).opcode := A_MOV;
  6863. taicpu(hp1).ops := 2;
  6864. taicpu(hp1).condition := C_None;
  6865. taicpu(hp1).opsize := S_B;
  6866. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6867. taicpu(hp1).loadconst(0, 0);
  6868. end;
  6869. end;
  6870. C_BE, C_NA:
  6871. begin
  6872. { Will only branch if equal to zero }
  6873. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  6874. taicpu(hp1).condition := C_E;
  6875. end;
  6876. C_A, C_NBE:
  6877. begin
  6878. { Will only branch if not equal to zero }
  6879. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  6880. taicpu(hp1).condition := C_NE;
  6881. end;
  6882. C_AE, C_NB, C_NC, C_NO:
  6883. begin
  6884. { Will always branch }
  6885. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  6886. if taicpu(hp1).opcode = A_Jcc then
  6887. begin
  6888. MakeUnconditional(taicpu(hp1));
  6889. { Any jumps/set that follow will now be dead code }
  6890. RemoveDeadCodeAfterJump(taicpu(hp1));
  6891. Break;
  6892. end
  6893. else
  6894. begin
  6895. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  6896. taicpu(hp1).opcode := A_MOV;
  6897. taicpu(hp1).ops := 2;
  6898. taicpu(hp1).condition := C_None;
  6899. taicpu(hp1).opsize := S_B;
  6900. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6901. taicpu(hp1).loadconst(0, 1);
  6902. end;
  6903. end;
  6904. C_None:
  6905. InternalError(2020012201);
  6906. C_P, C_PE, C_NP, C_PO:
  6907. { We can't handle parity checks and they should never be generated
  6908. after a general-purpose CMP (it's used in some floating-point
  6909. comparisons that don't use CMP) }
  6910. InternalError(2020012202);
  6911. else
  6912. { Zero/Equality, Sign, their complements and all of the
  6913. signed comparisons do not need to be converted };
  6914. end;
  6915. hp2 := hp1;
  6916. end;
  6917. { Convert the instruction to a TEST }
  6918. taicpu(p).opcode := A_TEST;
  6919. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6920. Result := True;
  6921. Exit;
  6922. end
  6923. else if (taicpu(p).oper[0]^.val = 1) and
  6924. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6925. (taicpu(hp1).condition in [C_L, C_NGE]) then
  6926. begin
  6927. { Convert; To:
  6928. cmp $1,r/m cmp $0,r/m
  6929. jl @lbl jle @lbl
  6930. }
  6931. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  6932. taicpu(p).oper[0]^.val := 0;
  6933. taicpu(hp1).condition := C_LE;
  6934. { If the instruction is now "cmp $0,%reg", convert it to a
  6935. TEST (and effectively do the work of the "cmp $0,%reg" in
  6936. the block above)
  6937. If it's a reference, we can get away with not setting
  6938. Result to True because he haven't evaluated the jump
  6939. in this pass yet.
  6940. }
  6941. if (taicpu(p).oper[1]^.typ = top_reg) then
  6942. begin
  6943. taicpu(p).opcode := A_TEST;
  6944. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  6945. Result := True;
  6946. end;
  6947. Exit;
  6948. end
  6949. else if (taicpu(p).oper[1]^.typ = top_reg)
  6950. {$ifdef x86_64}
  6951. and (taicpu(p).opsize <> S_Q) { S_Q will never happen: cmp with 64 bit constants is not possible }
  6952. {$endif x86_64}
  6953. then
  6954. begin
  6955. { cmp register,$8000 neg register
  6956. je target --> jo target
  6957. .... only if register is deallocated before jump.}
  6958. case Taicpu(p).opsize of
  6959. S_B: v:=$80;
  6960. S_W: v:=$8000;
  6961. S_L: v:=qword($80000000);
  6962. else
  6963. internalerror(2013112905);
  6964. end;
  6965. if (taicpu(p).oper[0]^.val=v) and
  6966. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  6967. (Taicpu(hp1).condition in [C_E,C_NE]) then
  6968. begin
  6969. TransferUsedRegs(TmpUsedRegs);
  6970. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  6971. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  6972. begin
  6973. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  6974. Taicpu(p).opcode:=A_NEG;
  6975. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  6976. Taicpu(p).clearop(1);
  6977. Taicpu(p).ops:=1;
  6978. if Taicpu(hp1).condition=C_E then
  6979. Taicpu(hp1).condition:=C_O
  6980. else
  6981. Taicpu(hp1).condition:=C_NO;
  6982. Result:=true;
  6983. exit;
  6984. end;
  6985. end;
  6986. end;
  6987. end;
  6988. if TrySwapMovCmp(p, hp1) then
  6989. begin
  6990. Result := True;
  6991. Exit;
  6992. end;
  6993. end;
  6994. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  6995. var
  6996. hp1: tai;
  6997. begin
  6998. {
  6999. remove the second (v)pxor from
  7000. pxor reg,reg
  7001. ...
  7002. pxor reg,reg
  7003. }
  7004. Result:=false;
  7005. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7006. MatchOpType(taicpu(p),top_reg,top_reg) and
  7007. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7008. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7009. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7010. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  7011. begin
  7012. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  7013. RemoveInstruction(hp1);
  7014. Result:=true;
  7015. Exit;
  7016. end
  7017. {
  7018. replace
  7019. pxor reg1,reg1
  7020. movapd/s reg1,reg2
  7021. dealloc reg1
  7022. by
  7023. pxor reg2,reg2
  7024. }
  7025. else if GetNextInstruction(p,hp1) and
  7026. { we mix single and double opperations here because we assume that the compiler
  7027. generates vmovapd only after double operations and vmovaps only after single operations }
  7028. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  7029. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7030. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  7031. (taicpu(p).oper[0]^.typ=top_reg) then
  7032. begin
  7033. TransferUsedRegs(TmpUsedRegs);
  7034. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7035. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7036. begin
  7037. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  7038. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  7039. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  7040. RemoveInstruction(hp1);
  7041. result:=true;
  7042. end;
  7043. end;
  7044. end;
  7045. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  7046. var
  7047. hp1: tai;
  7048. begin
  7049. {
  7050. remove the second (v)pxor from
  7051. (v)pxor reg,reg
  7052. ...
  7053. (v)pxor reg,reg
  7054. }
  7055. Result:=false;
  7056. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  7057. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7058. begin
  7059. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  7060. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  7061. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  7062. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  7063. begin
  7064. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2VPXor done',hp1);
  7065. RemoveInstruction(hp1);
  7066. Result:=true;
  7067. Exit;
  7068. end;
  7069. {$ifdef x86_64}
  7070. {
  7071. replace
  7072. vpxor reg1,reg1,reg1
  7073. vmov reg,mem
  7074. by
  7075. movq $0,mem
  7076. }
  7077. if GetNextInstruction(p,hp1) and
  7078. MatchInstruction(hp1,A_VMOVSD,[]) and
  7079. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7080. MatchOpType(taicpu(hp1),top_reg,top_ref) then
  7081. begin
  7082. TransferUsedRegs(TmpUsedRegs);
  7083. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7084. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7085. begin
  7086. taicpu(hp1).loadconst(0,0);
  7087. taicpu(hp1).opcode:=A_MOV;
  7088. taicpu(hp1).opsize:=S_Q;
  7089. DebugMsg(SPeepholeOptimization + 'VPXorVMov2Mov done',p);
  7090. RemoveCurrentP(p);
  7091. result:=true;
  7092. Exit;
  7093. end;
  7094. end;
  7095. {$endif x86_64}
  7096. end
  7097. {
  7098. replace
  7099. vpxor reg1,reg1,reg2
  7100. by
  7101. vpxor reg2,reg2,reg2
  7102. to avoid unncessary data dependencies
  7103. }
  7104. else if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  7105. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) then
  7106. begin
  7107. DebugMsg(SPeepholeOptimization + 'VPXor2VPXor done',p);
  7108. { avoid unncessary data dependency }
  7109. taicpu(p).loadreg(0,taicpu(p).oper[2]^.reg);
  7110. taicpu(p).loadreg(1,taicpu(p).oper[2]^.reg);
  7111. result:=true;
  7112. exit;
  7113. end;
  7114. Result:=OptPass1VOP(p);
  7115. end;
  7116. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  7117. var
  7118. hp1 : tai;
  7119. begin
  7120. result:=false;
  7121. { replace
  7122. IMul const,%mreg1,%mreg2
  7123. Mov %reg2,%mreg3
  7124. dealloc %mreg3
  7125. by
  7126. Imul const,%mreg1,%mreg23
  7127. }
  7128. if (taicpu(p).ops=3) and
  7129. GetNextInstruction(p,hp1) and
  7130. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7131. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7132. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7133. begin
  7134. TransferUsedRegs(TmpUsedRegs);
  7135. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7136. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7137. begin
  7138. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7139. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  7140. RemoveInstruction(hp1);
  7141. result:=true;
  7142. end;
  7143. end;
  7144. end;
  7145. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  7146. var
  7147. hp1 : tai;
  7148. begin
  7149. result:=false;
  7150. { replace
  7151. IMul %reg0,%reg1,%reg2
  7152. Mov %reg2,%reg3
  7153. dealloc %reg2
  7154. by
  7155. Imul %reg0,%reg1,%reg3
  7156. }
  7157. if GetNextInstruction(p,hp1) and
  7158. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  7159. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  7160. (taicpu(hp1).oper[1]^.typ=top_reg) then
  7161. begin
  7162. TransferUsedRegs(TmpUsedRegs);
  7163. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7164. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  7165. begin
  7166. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  7167. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  7168. RemoveInstruction(hp1);
  7169. result:=true;
  7170. end;
  7171. end;
  7172. end;
  7173. function TX86AsmOptimizer.OptPass1_V_Cvtss2sd(var p: tai): boolean;
  7174. var
  7175. hp1: tai;
  7176. begin
  7177. Result:=false;
  7178. { get rid of
  7179. (v)cvtss2sd reg0,<reg1,>reg2
  7180. (v)cvtss2sd reg2,<reg2,>reg0
  7181. }
  7182. if GetNextInstruction(p,hp1) and
  7183. (((taicpu(p).opcode=A_CVTSS2SD) and MatchInstruction(hp1,A_CVTSD2SS,[taicpu(p).opsize]) and
  7184. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)) or
  7185. ((taicpu(p).opcode=A_VCVTSS2SD) and MatchInstruction(hp1,A_VCVTSD2SS,[taicpu(p).opsize]) and
  7186. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  7187. MatchOpType(taicpu(hp1),top_reg,top_reg,top_reg) and
  7188. (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7189. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  7190. (getsupreg(taicpu(p).oper[2]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg))
  7191. )
  7192. ) then
  7193. begin
  7194. if ((taicpu(p).opcode=A_CVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7195. ((taicpu(p).opcode=A_VCVTSS2SD) and (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[2]^.reg))) then
  7196. begin
  7197. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Nop done',p);
  7198. RemoveCurrentP(p);
  7199. RemoveInstruction(hp1);
  7200. end
  7201. else
  7202. begin
  7203. DebugMsg(SPeepholeOptimization + '(V)Cvtss2CvtSd(V)Cvtsd2ss2Vmovaps done',p);
  7204. if taicpu(hp1).opcode=A_CVTSD2SS then
  7205. begin
  7206. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7207. taicpu(p).opcode:=A_MOVAPS;
  7208. end
  7209. else
  7210. begin
  7211. taicpu(p).loadreg(1,taicpu(hp1).oper[2]^.reg);
  7212. taicpu(p).opcode:=A_VMOVAPS;
  7213. end;
  7214. taicpu(p).ops:=2;
  7215. RemoveInstruction(hp1);
  7216. end;
  7217. Result:=true;
  7218. Exit;
  7219. end;
  7220. end;
  7221. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  7222. var
  7223. hp1, hp2, hp3, hp4, hp5, hp6: tai;
  7224. ThisReg: TRegister;
  7225. begin
  7226. Result := False;
  7227. if not GetNextInstruction(p,hp1) then
  7228. Exit;
  7229. {
  7230. convert
  7231. j<c> .L1
  7232. mov 1,reg
  7233. jmp .L2
  7234. .L1
  7235. mov 0,reg
  7236. .L2
  7237. into
  7238. mov 0,reg
  7239. set<not(c)> reg
  7240. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7241. would destroy the flag contents
  7242. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  7243. executed at the same time as a previous comparison.
  7244. set<not(c)> reg
  7245. movzx reg, reg
  7246. }
  7247. if MatchInstruction(hp1,A_MOV,[]) and
  7248. (taicpu(hp1).oper[0]^.typ = top_const) and
  7249. (
  7250. (
  7251. (taicpu(hp1).oper[1]^.typ = top_reg)
  7252. {$ifdef i386}
  7253. { Under i386, ESI, EDI, EBP and ESP
  7254. don't have an 8-bit representation }
  7255. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7256. {$endif i386}
  7257. ) or (
  7258. {$ifdef i386}
  7259. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  7260. {$endif i386}
  7261. (taicpu(hp1).opsize = S_B)
  7262. )
  7263. ) and
  7264. GetNextInstruction(hp1,hp2) and
  7265. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7266. GetNextInstruction(hp2,hp3) and
  7267. SkipAligns(hp3, hp3) and
  7268. (hp3.typ=ait_label) and
  7269. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7270. GetNextInstruction(hp3,hp4) and
  7271. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  7272. (taicpu(hp4).oper[0]^.typ = top_const) and
  7273. (
  7274. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  7275. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  7276. ) and
  7277. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7278. GetNextInstruction(hp4,hp5) and
  7279. SkipAligns(hp5, hp5) and
  7280. (hp5.typ=ait_label) and
  7281. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  7282. begin
  7283. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7284. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7285. tai_label(hp3).labsym.DecRefs;
  7286. { If this isn't the only reference to the middle label, we can
  7287. still make a saving - only that the first jump and everything
  7288. that follows will remain. }
  7289. if (tai_label(hp3).labsym.getrefs = 0) then
  7290. begin
  7291. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7292. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  7293. else
  7294. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  7295. { remove jump, first label and second MOV (also catching any aligns) }
  7296. repeat
  7297. if not GetNextInstruction(hp2, hp3) then
  7298. InternalError(2021040810);
  7299. RemoveInstruction(hp2);
  7300. hp2 := hp3;
  7301. until hp2 = hp5;
  7302. { Don't decrement reference count before the removal loop
  7303. above, otherwise GetNextInstruction won't stop on the
  7304. the label }
  7305. tai_label(hp5).labsym.DecRefs;
  7306. end
  7307. else
  7308. begin
  7309. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  7310. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  7311. else
  7312. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  7313. end;
  7314. taicpu(p).opcode:=A_SETcc;
  7315. taicpu(p).opsize:=S_B;
  7316. taicpu(p).is_jmp:=False;
  7317. if taicpu(hp1).opsize=S_B then
  7318. begin
  7319. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  7320. if taicpu(hp1).oper[1]^.typ = top_reg then
  7321. AllocRegBetween(taicpu(hp1).oper[1]^.reg, p, hp2, UsedRegs);
  7322. RemoveInstruction(hp1);
  7323. end
  7324. else
  7325. begin
  7326. { Will be a register because the size can't be S_B otherwise }
  7327. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  7328. taicpu(p).loadreg(0, ThisReg);
  7329. AllocRegBetween(ThisReg, p, hp2, UsedRegs);
  7330. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  7331. begin
  7332. case taicpu(hp1).opsize of
  7333. S_W:
  7334. taicpu(hp1).opsize := S_BW;
  7335. S_L:
  7336. taicpu(hp1).opsize := S_BL;
  7337. {$ifdef x86_64}
  7338. S_Q:
  7339. begin
  7340. taicpu(hp1).opsize := S_BL;
  7341. { Change the destination register to 32-bit }
  7342. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  7343. end;
  7344. {$endif x86_64}
  7345. else
  7346. InternalError(2021040820);
  7347. end;
  7348. taicpu(hp1).opcode := A_MOVZX;
  7349. taicpu(hp1).loadreg(0, ThisReg);
  7350. end
  7351. else
  7352. begin
  7353. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  7354. { hp1 is already a MOV instruction with the correct register }
  7355. taicpu(hp1).loadconst(0, 0);
  7356. { Inserting it right before p will guarantee that the flags are also tracked }
  7357. asml.Remove(hp1);
  7358. asml.InsertBefore(hp1, p);
  7359. end;
  7360. end;
  7361. Result:=true;
  7362. exit;
  7363. end
  7364. else if (hp1.typ = ait_label) then
  7365. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  7366. end;
  7367. function TX86AsmOptimizer.OptPass1VMOVDQ(var p: tai): Boolean;
  7368. var
  7369. hp1, hp2, hp3: tai;
  7370. SourceRef, TargetRef: TReference;
  7371. CurrentReg: TRegister;
  7372. begin
  7373. { VMOVDQU/CMOVDQA shouldn't have even been generated }
  7374. if not UseAVX then
  7375. InternalError(2021100501);
  7376. Result := False;
  7377. { Look for the following to simplify:
  7378. vmovdqa/u x(mem1), %xmmreg
  7379. vmovdqa/u %xmmreg, y(mem2)
  7380. vmovdqa/u x+16(mem1), %xmmreg
  7381. vmovdqa/u %xmmreg, y+16(mem2)
  7382. Change to:
  7383. vmovdqa/u x(mem1), %ymmreg
  7384. vmovdqa/u %ymmreg, y(mem2)
  7385. vpxor %ymmreg, %ymmreg, %ymmreg
  7386. ( The VPXOR instruction is to zero the upper half, thus removing the
  7387. need to call the potentially expensive VZEROUPPER instruction. Other
  7388. peephole optimisations can remove VPXOR if it's unnecessary )
  7389. }
  7390. TransferUsedRegs(TmpUsedRegs);
  7391. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  7392. { NOTE: In the optimisations below, if the references dictate that an
  7393. aligned move is possible (i.e. VMOVDQA), the existing instructions
  7394. should already be VMOVDQA because if (x mod 32) = 0, then (x mod 16) = 0 }
  7395. if (taicpu(p).opsize = S_XMM) and
  7396. MatchOpType(taicpu(p), top_ref, top_reg) and
  7397. GetNextInstruction(p, hp1) and
  7398. MatchInstruction(hp1, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7399. MatchOpType(taicpu(hp1), top_reg, top_ref) and
  7400. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  7401. begin
  7402. SourceRef := taicpu(p).oper[0]^.ref^;
  7403. TargetRef := taicpu(hp1).oper[1]^.ref^;
  7404. if GetNextInstruction(hp1, hp2) and
  7405. MatchInstruction(hp2, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7406. MatchOpType(taicpu(hp2), top_ref, top_reg) then
  7407. begin
  7408. { Delay calling GetNextInstruction(hp2, hp3) for as long as possible }
  7409. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  7410. Inc(SourceRef.offset, 16);
  7411. { Reuse the register in the first block move }
  7412. CurrentReg := newreg(R_MMREGISTER, getsupreg(taicpu(p).oper[1]^.reg), R_SUBMMY);
  7413. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) and
  7414. not RefsMightOverlap(taicpu(p).oper[0]^.ref^, TargetRef, 32) then
  7415. begin
  7416. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7417. Inc(TargetRef.offset, 16);
  7418. if GetNextInstruction(hp2, hp3) and
  7419. MatchInstruction(hp3, A_VMOVDQA, A_VMOVDQU, [S_XMM]) and
  7420. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7421. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7422. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7423. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7424. begin
  7425. { Update the register tracking to the new size }
  7426. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  7427. { Remember that the offsets are 16 ahead }
  7428. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7429. if not (
  7430. ((SourceRef.offset mod 32) = 16) and
  7431. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7432. ) then
  7433. taicpu(p).opcode := A_VMOVDQU;
  7434. taicpu(p).opsize := S_YMM;
  7435. taicpu(p).oper[1]^.reg := CurrentReg;
  7436. if not (
  7437. ((TargetRef.offset mod 32) = 16) and
  7438. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7439. ) then
  7440. taicpu(hp1).opcode := A_VMOVDQU;
  7441. taicpu(hp1).opsize := S_YMM;
  7442. taicpu(hp1).oper[0]^.reg := CurrentReg;
  7443. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 1)', p);
  7444. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7445. if (pi_uses_ymm in current_procinfo.flags) then
  7446. RemoveInstruction(hp2)
  7447. else
  7448. begin
  7449. taicpu(hp2).opcode := A_VPXOR;
  7450. taicpu(hp2).opsize := S_YMM;
  7451. taicpu(hp2).loadreg(0, CurrentReg);
  7452. taicpu(hp2).loadreg(1, CurrentReg);
  7453. taicpu(hp2).loadreg(2, CurrentReg);
  7454. taicpu(hp2).ops := 3;
  7455. end;
  7456. RemoveInstruction(hp3);
  7457. Result := True;
  7458. Exit;
  7459. end;
  7460. end
  7461. else
  7462. begin
  7463. { See if the next references are 16 less rather than 16 greater }
  7464. Dec(SourceRef.offset, 32); { -16 the other way }
  7465. if RefsEqual(SourceRef, taicpu(hp2).oper[0]^.ref^) then
  7466. begin
  7467. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  7468. Dec(TargetRef.offset, 16); { Only 16, not 32, as it wasn't incremented unlike SourceRef }
  7469. if not RefsMightOverlap(SourceRef, TargetRef, 32) and
  7470. GetNextInstruction(hp2, hp3) and
  7471. MatchInstruction(hp3, A_MOV, [taicpu(p).opsize]) and
  7472. MatchOpType(taicpu(hp3), top_reg, top_ref) and
  7473. (taicpu(hp2).oper[1]^.reg = taicpu(hp3).oper[0]^.reg) and
  7474. RefsEqual(TargetRef, taicpu(hp3).oper[1]^.ref^) and
  7475. not RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp3, TmpUsedRegs) then
  7476. begin
  7477. { Update the register tracking to the new size }
  7478. AllocRegBetween(CurrentReg, hp2, hp3, UsedRegs);
  7479. { hp2 and hp3 are the starting offsets, so mod = 0 this time }
  7480. { Switch to unaligned if the memory isn't on a 32-byte boundary }
  7481. if not(
  7482. ((SourceRef.offset mod 32) = 0) and
  7483. (SourceRef.alignment >= 32) and ((SourceRef.alignment mod 32) = 0)
  7484. ) then
  7485. taicpu(hp2).opcode := A_VMOVDQU;
  7486. taicpu(hp2).opsize := S_YMM;
  7487. taicpu(hp2).oper[1]^.reg := CurrentReg;
  7488. if not (
  7489. ((TargetRef.offset mod 32) = 0) and
  7490. (TargetRef.alignment >= 32) and ((TargetRef.alignment mod 32) = 0)
  7491. ) then
  7492. taicpu(hp3).opcode := A_VMOVDQU;
  7493. taicpu(hp3).opsize := S_YMM;
  7494. taicpu(hp3).oper[0]^.reg := CurrentReg;
  7495. DebugMsg(SPeepholeOptimization + 'Used ' + debug_regname(CurrentReg) + ' to merge a pair of memory moves (VmovdqxVmovdqxVmovdqxVmovdqx2VmovdqyVmovdqy 2)', p);
  7496. { If pi_uses_ymm is set, VZEROUPPER is present to do this for us }
  7497. if (pi_uses_ymm in current_procinfo.flags) then
  7498. RemoveInstruction(hp1)
  7499. else
  7500. begin
  7501. taicpu(hp1).opcode := A_VPXOR;
  7502. taicpu(hp1).opsize := S_YMM;
  7503. taicpu(hp1).loadreg(0, CurrentReg);
  7504. taicpu(hp1).loadreg(1, CurrentReg);
  7505. taicpu(hp1).loadreg(2, CurrentReg);
  7506. taicpu(hp1).ops := 3;
  7507. Asml.Remove(hp1);
  7508. Asml.InsertAfter(hp1, hp3); { Register deallocations will be after hp3 }
  7509. end;
  7510. RemoveCurrentP(p, hp2);
  7511. Result := True;
  7512. Exit;
  7513. end;
  7514. end;
  7515. end;
  7516. end;
  7517. end;
  7518. end;
  7519. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  7520. var
  7521. hp2, hp3, first_assignment: tai;
  7522. IncCount, OperIdx: Integer;
  7523. OrigLabel: TAsmLabel;
  7524. begin
  7525. Count := 0;
  7526. Result := False;
  7527. first_assignment := nil;
  7528. if (LoopCount >= 20) then
  7529. begin
  7530. { Guard against infinite loops }
  7531. Exit;
  7532. end;
  7533. if (taicpu(p).oper[0]^.typ <> top_ref) or
  7534. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  7535. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  7536. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  7537. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  7538. Exit;
  7539. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7540. {
  7541. change
  7542. jmp .L1
  7543. ...
  7544. .L1:
  7545. mov ##, ## ( multiple movs possible )
  7546. jmp/ret
  7547. into
  7548. mov ##, ##
  7549. jmp/ret
  7550. }
  7551. if not Assigned(hp1) then
  7552. begin
  7553. hp1 := GetLabelWithSym(OrigLabel);
  7554. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  7555. Exit;
  7556. end;
  7557. hp2 := hp1;
  7558. while Assigned(hp2) do
  7559. begin
  7560. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  7561. SkipLabels(hp2,hp2);
  7562. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  7563. Break;
  7564. case taicpu(hp2).opcode of
  7565. A_MOVSS:
  7566. begin
  7567. if taicpu(hp2).ops = 0 then
  7568. { Wrong MOVSS }
  7569. Break;
  7570. Inc(Count);
  7571. if Count >= 5 then
  7572. { Too many to be worthwhile }
  7573. Break;
  7574. GetNextInstruction(hp2, hp2);
  7575. Continue;
  7576. end;
  7577. A_MOV,
  7578. A_MOVD,
  7579. A_MOVQ,
  7580. A_MOVSX,
  7581. {$ifdef x86_64}
  7582. A_MOVSXD,
  7583. {$endif x86_64}
  7584. A_MOVZX,
  7585. A_MOVAPS,
  7586. A_MOVUPS,
  7587. A_MOVSD,
  7588. A_MOVAPD,
  7589. A_MOVUPD,
  7590. A_MOVDQA,
  7591. A_MOVDQU,
  7592. A_VMOVSS,
  7593. A_VMOVAPS,
  7594. A_VMOVUPS,
  7595. A_VMOVSD,
  7596. A_VMOVAPD,
  7597. A_VMOVUPD,
  7598. A_VMOVDQA,
  7599. A_VMOVDQU:
  7600. begin
  7601. Inc(Count);
  7602. if Count >= 5 then
  7603. { Too many to be worthwhile }
  7604. Break;
  7605. GetNextInstruction(hp2, hp2);
  7606. Continue;
  7607. end;
  7608. A_JMP:
  7609. begin
  7610. { Guard against infinite loops }
  7611. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  7612. Exit;
  7613. { Analyse this jump first in case it also duplicates assignments }
  7614. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  7615. begin
  7616. { Something did change! }
  7617. Result := True;
  7618. Inc(Count, IncCount);
  7619. if Count >= 5 then
  7620. begin
  7621. { Too many to be worthwhile }
  7622. Exit;
  7623. end;
  7624. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  7625. Break;
  7626. end;
  7627. Result := True;
  7628. Break;
  7629. end;
  7630. A_RET:
  7631. begin
  7632. Result := True;
  7633. Break;
  7634. end;
  7635. else
  7636. Break;
  7637. end;
  7638. end;
  7639. if Result then
  7640. begin
  7641. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  7642. if Count = 0 then
  7643. begin
  7644. Result := False;
  7645. Exit;
  7646. end;
  7647. hp3 := p;
  7648. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  7649. while True do
  7650. begin
  7651. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  7652. SkipLabels(hp1,hp1);
  7653. if (hp1.typ <> ait_instruction) then
  7654. InternalError(2021040720);
  7655. case taicpu(hp1).opcode of
  7656. A_JMP:
  7657. begin
  7658. { Change the original jump to the new destination }
  7659. OrigLabel.decrefs;
  7660. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  7661. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  7662. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7663. if not Assigned(first_assignment) then
  7664. InternalError(2021040810)
  7665. else
  7666. p := first_assignment;
  7667. Exit;
  7668. end;
  7669. A_RET:
  7670. begin
  7671. { Now change the jump into a RET instruction }
  7672. ConvertJumpToRET(p, hp1);
  7673. { Set p to the first duplicated assignment so it can get optimised if needs be }
  7674. if not Assigned(first_assignment) then
  7675. InternalError(2021040811)
  7676. else
  7677. p := first_assignment;
  7678. Exit;
  7679. end;
  7680. else
  7681. begin
  7682. { Duplicate the MOV instruction }
  7683. hp3:=tai(hp1.getcopy);
  7684. if first_assignment = nil then
  7685. first_assignment := hp3;
  7686. asml.InsertBefore(hp3, p);
  7687. { Make sure the compiler knows about any final registers written here }
  7688. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  7689. with taicpu(hp3).oper[OperIdx]^ do
  7690. begin
  7691. case typ of
  7692. top_ref:
  7693. begin
  7694. if (ref^.base <> NR_NO) and
  7695. (getsupreg(ref^.base) <> RS_ESP) and
  7696. (getsupreg(ref^.base) <> RS_EBP)
  7697. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  7698. then
  7699. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  7700. if (ref^.index <> NR_NO) and
  7701. (getsupreg(ref^.index) <> RS_ESP) and
  7702. (getsupreg(ref^.index) <> RS_EBP)
  7703. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  7704. (ref^.index <> ref^.base) then
  7705. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  7706. end;
  7707. top_reg:
  7708. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  7709. else
  7710. ;
  7711. end;
  7712. end;
  7713. end;
  7714. end;
  7715. if not GetNextInstruction(hp1, hp1) then
  7716. { Should have dropped out earlier }
  7717. InternalError(2021040710);
  7718. end;
  7719. end;
  7720. end;
  7721. function TX86AsmOptimizer.TrySwapMovCmp(var p, hp1: tai): Boolean;
  7722. var
  7723. hp2: tai;
  7724. X: Integer;
  7725. const
  7726. WriteOp: array[0..3] of set of TInsChange = (
  7727. [Ch_Wop1, Ch_RWop1, Ch_Mop1],
  7728. [Ch_Wop2, Ch_RWop2, Ch_Mop2],
  7729. [Ch_Wop3, Ch_RWop3, Ch_Mop3],
  7730. [Ch_Wop4, Ch_RWop4, Ch_Mop4]);
  7731. RegWriteFlags: array[0..7] of set of TInsChange = (
  7732. { The order is important: EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP }
  7733. [Ch_WEAX, Ch_RWEAX, Ch_MEAX{$ifdef x86_64}, Ch_WRAX, Ch_RWRAX, Ch_MRAX{$endif x86_64}],
  7734. [Ch_WECX, Ch_RWECX, Ch_MECX{$ifdef x86_64}, Ch_WRCX, Ch_RWRCX, Ch_MRCX{$endif x86_64}],
  7735. [Ch_WEDX, Ch_RWEDX, Ch_MEDX{$ifdef x86_64}, Ch_WRDX, Ch_RWRDX, Ch_MRDX{$endif x86_64}],
  7736. [Ch_WEBX, Ch_RWEBX, Ch_MEBX{$ifdef x86_64}, Ch_WRBX, Ch_RWRBX, Ch_MRBX{$endif x86_64}],
  7737. [Ch_WESI, Ch_RWESI, Ch_MESI{$ifdef x86_64}, Ch_WRSI, Ch_RWRSI, Ch_MRSI{$endif x86_64}],
  7738. [Ch_WEDI, Ch_RWEDI, Ch_MEDI{$ifdef x86_64}, Ch_WRDI, Ch_RWRDI, Ch_MRDI{$endif x86_64}],
  7739. [Ch_WEBP, Ch_RWEBP, Ch_MEBP{$ifdef x86_64}, Ch_WRBP, Ch_RWRBP, Ch_MRBP{$endif x86_64}],
  7740. [Ch_WESP, Ch_RWESP, Ch_MESP{$ifdef x86_64}, Ch_WRSP, Ch_RWRSP, Ch_MRSP{$endif x86_64}]);
  7741. begin
  7742. { If we have something like:
  7743. cmp ###,%reg1
  7744. mov 0,%reg2
  7745. And no modified registers are shared, move the instruction to before
  7746. the comparison as this means it can be optimised without worrying
  7747. about the FLAGS register. (CMP/MOV is generated by
  7748. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  7749. As long as the second instruction doesn't use the flags or one of the
  7750. registers used by CMP or TEST (also check any references that use the
  7751. registers), then it can be moved prior to the comparison.
  7752. }
  7753. Result := False;
  7754. if (hp1.typ <> ait_instruction) or
  7755. taicpu(hp1).is_jmp or
  7756. RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  7757. Exit;
  7758. { NOP is a pipeline fence, likely marking the beginning of the function
  7759. epilogue, so drop out. Similarly, drop out if POP or RET are
  7760. encountered }
  7761. if MatchInstruction(hp1, A_NOP, A_POP, []) then
  7762. Exit;
  7763. if (taicpu(hp1).opcode = A_MOVSS) and
  7764. (taicpu(hp1).ops = 0) then
  7765. { Wrong MOVSS }
  7766. Exit;
  7767. { Check for writes to specific registers first }
  7768. { EAX, ECX, EDX, EBX, ESI, EDI, EBP, ESP in that order }
  7769. for X := 0 to 7 do
  7770. if (RegWriteFlags[X] * InsProp[taicpu(hp1).opcode].Ch <> [])
  7771. and RegInInstruction(newreg(R_INTREGISTER, TSuperRegister(X), R_SUBWHOLE), p) then
  7772. Exit;
  7773. for X := 0 to taicpu(hp1).ops - 1 do
  7774. begin
  7775. { Check to see if this operand writes to something }
  7776. if ((WriteOp[X] * InsProp[taicpu(hp1).opcode].Ch) <> []) and
  7777. { And matches something in the CMP/TEST instruction }
  7778. (
  7779. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[0]^) or
  7780. MatchOperand(taicpu(hp1).oper[X]^, taicpu(p).oper[1]^) or
  7781. (
  7782. { If it's a register, make sure the register written to doesn't
  7783. appear in the cmp instruction as part of a reference }
  7784. (taicpu(hp1).oper[X]^.typ = top_reg) and
  7785. RegInInstruction(taicpu(hp1).oper[X]^.reg, p)
  7786. )
  7787. ) then
  7788. Exit;
  7789. end;
  7790. { The instruction can be safely moved }
  7791. asml.Remove(hp1);
  7792. { Try to insert before the FLAGS register is allocated, so "mov $0,%reg"
  7793. can be optimised into "xor %reg,%reg" later }
  7794. if SetAndTest(FindRegAllocBackward(NR_DEFAULTFLAGS, tai(p.Previous)), hp2) then
  7795. asml.InsertBefore(hp1, hp2)
  7796. else
  7797. { Note, if p.Previous is nil (even if it should logically never be the
  7798. case), FindRegAllocBackward immediately exits with False and so we
  7799. safely land here (we can't just pass p because FindRegAllocBackward
  7800. immediately exits on an instruction). [Kit] }
  7801. asml.InsertBefore(hp1, p);
  7802. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and ' + debug_op2str(taicpu(hp1).opcode) + ' instructions to improve optimisation potential', hp1);
  7803. for X := 0 to taicpu(hp1).ops - 1 do
  7804. case taicpu(hp1).oper[X]^.typ of
  7805. top_reg:
  7806. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  7807. top_ref:
  7808. begin
  7809. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  7810. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  7811. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  7812. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  7813. end;
  7814. else
  7815. ;
  7816. end;
  7817. if taicpu(hp1).opcode = A_LEA then
  7818. { The flags will be overwritten by the CMP/TEST instruction }
  7819. ConvertLEA(taicpu(hp1));
  7820. Result := True;
  7821. end;
  7822. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  7823. function IsXCHGAcceptable: Boolean; inline;
  7824. begin
  7825. { Always accept if optimising for size }
  7826. Result := (cs_opt_size in current_settings.optimizerswitches) or
  7827. (
  7828. {$ifdef x86_64}
  7829. { XCHG takes 3 cycles on AMD Athlon64 }
  7830. (current_settings.optimizecputype >= cpu_core_i)
  7831. {$else x86_64}
  7832. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  7833. than 3, so it becomes a saving compared to three MOVs with two of
  7834. them able to execute simultaneously. [Kit] }
  7835. (current_settings.optimizecputype >= cpu_PentiumM)
  7836. {$endif x86_64}
  7837. );
  7838. end;
  7839. var
  7840. NewRef: TReference;
  7841. hp1, hp2, hp3, hp4: Tai;
  7842. {$ifndef x86_64}
  7843. OperIdx: Integer;
  7844. {$endif x86_64}
  7845. NewInstr : Taicpu;
  7846. NewAligh : Tai_align;
  7847. DestLabel: TAsmLabel;
  7848. function TryMovArith2Lea(InputInstr: tai): Boolean;
  7849. var
  7850. NextInstr: tai;
  7851. begin
  7852. Result := False;
  7853. UpdateUsedRegs(TmpUsedRegs, tai(InputInstr.Next));
  7854. if not GetNextInstruction(InputInstr, NextInstr) or
  7855. (
  7856. { The FLAGS register isn't always tracked properly, so do not
  7857. perform this optimisation if a conditional statement follows }
  7858. not RegReadByInstruction(NR_DEFAULTFLAGS, NextInstr) and
  7859. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, NextInstr, TmpUsedRegs)
  7860. ) then
  7861. begin
  7862. reference_reset(NewRef, 1, []);
  7863. NewRef.base := taicpu(p).oper[0]^.reg;
  7864. NewRef.scalefactor := 1;
  7865. if taicpu(InputInstr).opcode = A_ADD then
  7866. begin
  7867. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  7868. NewRef.offset := taicpu(InputInstr).oper[0]^.val;
  7869. end
  7870. else
  7871. begin
  7872. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  7873. NewRef.offset := -taicpu(InputInstr).oper[0]^.val;
  7874. end;
  7875. taicpu(p).opcode := A_LEA;
  7876. taicpu(p).loadref(0, NewRef);
  7877. RemoveInstruction(InputInstr);
  7878. Result := True;
  7879. end;
  7880. end;
  7881. begin
  7882. Result:=false;
  7883. { This optimisation adds an instruction, so only do it for speed }
  7884. if not (cs_opt_size in current_settings.optimizerswitches) and
  7885. MatchOpType(taicpu(p), top_const, top_reg) and
  7886. (taicpu(p).oper[0]^.val = 0) then
  7887. begin
  7888. { To avoid compiler warning }
  7889. DestLabel := nil;
  7890. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  7891. InternalError(2021040750);
  7892. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  7893. Exit;
  7894. case hp1.typ of
  7895. ait_align,
  7896. ait_label:
  7897. begin
  7898. { Change:
  7899. mov $0,%reg mov $0,%reg
  7900. @Lbl1: @Lbl1:
  7901. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  7902. je @Lbl2 jne @Lbl2
  7903. To: To:
  7904. mov $0,%reg mov $0,%reg
  7905. jmp @Lbl2 jmp @Lbl3
  7906. (align) (align)
  7907. @Lbl1: @Lbl1:
  7908. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  7909. je @Lbl2 je @Lbl2
  7910. @Lbl3: <-- Only if label exists
  7911. (Not if it's optimised for size)
  7912. }
  7913. if not SkipAligns(hp1, hp1) or not GetNextInstruction(hp1, hp2) then
  7914. Exit;
  7915. if (hp2.typ = ait_instruction) and
  7916. (
  7917. { Register sizes must exactly match }
  7918. (
  7919. (taicpu(hp2).opcode = A_CMP) and
  7920. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  7921. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7922. ) or (
  7923. (taicpu(hp2).opcode = A_TEST) and
  7924. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  7925. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  7926. )
  7927. ) and GetNextInstruction(hp2, hp3) and
  7928. (hp3.typ = ait_instruction) and
  7929. (taicpu(hp3).opcode = A_JCC) and
  7930. (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
  7931. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  7932. begin
  7933. { Check condition of jump }
  7934. { Always true? }
  7935. if condition_in(C_E, taicpu(hp3).condition) then
  7936. begin
  7937. { Copy label symbol and obtain matching label entry for the
  7938. conditional jump, as this will be our destination}
  7939. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  7940. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  7941. Result := True;
  7942. end
  7943. { Always false? }
  7944. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  7945. begin
  7946. { This is only worth it if there's a jump to take }
  7947. case hp2.typ of
  7948. ait_instruction:
  7949. begin
  7950. if taicpu(hp2).opcode = A_JMP then
  7951. begin
  7952. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7953. { An unconditional jump follows the conditional jump which will always be false,
  7954. so use this jump's destination for the new jump }
  7955. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  7956. Result := True;
  7957. end
  7958. else if taicpu(hp2).opcode = A_JCC then
  7959. begin
  7960. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  7961. if condition_in(C_E, taicpu(hp2).condition) then
  7962. begin
  7963. { A second conditional jump follows the conditional jump which will always be false,
  7964. while the second jump is always True, so use this jump's destination for the new jump }
  7965. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  7966. Result := True;
  7967. end;
  7968. { Don't risk it if the jump isn't always true (Result remains False) }
  7969. end;
  7970. end;
  7971. else
  7972. { If anything else don't optimise };
  7973. end;
  7974. end;
  7975. if Result then
  7976. begin
  7977. { Just so we have something to insert as a paremeter}
  7978. reference_reset(NewRef, 1, []);
  7979. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  7980. { Now actually load the correct parameter (this also
  7981. increases the reference count) }
  7982. NewInstr.loadsymbol(0, DestLabel, 0);
  7983. if (cs_opt_level3 in current_settings.optimizerswitches) then
  7984. begin
  7985. { Get instruction before original label (may not be p under -O3) }
  7986. if not GetLastInstruction(hp1, hp2) then
  7987. { Shouldn't fail here }
  7988. InternalError(2021040701);
  7989. { Before the aligns too }
  7990. while (hp2.typ = ait_align) do
  7991. if not GetLastInstruction(hp2, hp2) then
  7992. { Shouldn't fail here }
  7993. InternalError(2021040702);
  7994. end
  7995. else
  7996. hp2 := p;
  7997. taicpu(NewInstr).fileinfo := taicpu(hp2).fileinfo;
  7998. AsmL.InsertAfter(NewInstr, hp2);
  7999. { Add new alignment field }
  8000. (* AsmL.InsertAfter(
  8001. cai_align.create_max(
  8002. current_settings.alignment.jumpalign,
  8003. current_settings.alignment.jumpalignskipmax
  8004. ),
  8005. NewInstr
  8006. ); *)
  8007. end;
  8008. Exit;
  8009. end;
  8010. end;
  8011. else
  8012. ;
  8013. end;
  8014. end;
  8015. if not GetNextInstruction(p, hp1) then
  8016. Exit;
  8017. if MatchInstruction(hp1, A_CMP, A_TEST, [taicpu(p).opsize])
  8018. and DoMovCmpMemOpt(p, hp1, True) then
  8019. begin
  8020. Result := True;
  8021. Exit;
  8022. end
  8023. else if MatchInstruction(hp1, A_JMP, [S_NO]) then
  8024. begin
  8025. { Sometimes the MOVs that OptPass2JMP produces can be improved
  8026. further, but we can't just put this jump optimisation in pass 1
  8027. because it tends to perform worse when conditional jumps are
  8028. nearby (e.g. when converting CMOV instructions). [Kit] }
  8029. if OptPass2JMP(hp1) then
  8030. { call OptPass1MOV once to potentially merge any MOVs that were created }
  8031. Result := OptPass1MOV(p)
  8032. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  8033. returned True and the instruction is still a MOV, thus checking
  8034. the optimisations below }
  8035. { If OptPass2JMP returned False, no optimisations were done to
  8036. the jump and there are no further optimisations that can be done
  8037. to the MOV instruction on this pass }
  8038. end
  8039. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8040. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8041. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8042. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8043. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  8044. begin
  8045. { Change:
  8046. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  8047. addl/q $x,%reg2 subl/q $x,%reg2
  8048. To:
  8049. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  8050. }
  8051. if (taicpu(hp1).oper[0]^.typ = top_const) and
  8052. { be lazy, checking separately for sub would be slightly better }
  8053. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  8054. begin
  8055. TransferUsedRegs(TmpUsedRegs);
  8056. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8057. if TryMovArith2Lea(hp1) then
  8058. begin
  8059. Result := True;
  8060. Exit;
  8061. end
  8062. end
  8063. else if not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) and
  8064. GetNextInstructionUsingReg(hp1, hp2, taicpu(p).oper[1]^.reg) and
  8065. { Same as above, but also adds or subtracts to %reg2 in between.
  8066. It's still valid as long as the flags aren't in use }
  8067. MatchInstruction(hp2,A_ADD,A_SUB,[taicpu(p).opsize]) and
  8068. MatchOpType(taicpu(hp2), top_const, top_reg) and
  8069. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  8070. { be lazy, checking separately for sub would be slightly better }
  8071. (abs(taicpu(hp2).oper[0]^.val)<=$7fffffff) then
  8072. begin
  8073. TransferUsedRegs(TmpUsedRegs);
  8074. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8075. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8076. if TryMovArith2Lea(hp2) then
  8077. begin
  8078. Result := True;
  8079. Exit;
  8080. end;
  8081. end;
  8082. end
  8083. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8084. {$ifdef x86_64}
  8085. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  8086. {$else x86_64}
  8087. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  8088. {$endif x86_64}
  8089. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8090. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  8091. { mov reg1, reg2 mov reg1, reg2
  8092. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  8093. begin
  8094. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  8095. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  8096. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  8097. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  8098. TransferUsedRegs(TmpUsedRegs);
  8099. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  8100. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  8101. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  8102. then
  8103. begin
  8104. RemoveCurrentP(p, hp1);
  8105. Result:=true;
  8106. end;
  8107. exit;
  8108. end
  8109. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8110. IsXCHGAcceptable and
  8111. { XCHG doesn't support 8-byte registers }
  8112. (taicpu(p).opsize <> S_B) and
  8113. MatchInstruction(hp1, A_MOV, []) and
  8114. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8115. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  8116. GetNextInstruction(hp1, hp2) and
  8117. MatchInstruction(hp2, A_MOV, []) and
  8118. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  8119. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  8120. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  8121. begin
  8122. { mov %reg1,%reg2
  8123. mov %reg3,%reg1 -> xchg %reg3,%reg1
  8124. mov %reg2,%reg3
  8125. (%reg2 not used afterwards)
  8126. Note that xchg takes 3 cycles to execute, and generally mov's take
  8127. only one cycle apiece, but the first two mov's can be executed in
  8128. parallel, only taking 2 cycles overall. Older processors should
  8129. therefore only optimise for size. [Kit]
  8130. }
  8131. TransferUsedRegs(TmpUsedRegs);
  8132. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8133. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8134. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  8135. begin
  8136. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  8137. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  8138. taicpu(hp1).opcode := A_XCHG;
  8139. RemoveCurrentP(p, hp1);
  8140. RemoveInstruction(hp2);
  8141. Result := True;
  8142. Exit;
  8143. end;
  8144. end
  8145. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  8146. MatchInstruction(hp1, A_SAR, []) then
  8147. begin
  8148. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  8149. begin
  8150. { the use of %edx also covers the opsize being S_L }
  8151. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  8152. begin
  8153. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  8154. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  8155. (taicpu(p).oper[1]^.reg = NR_EDX) then
  8156. begin
  8157. { Change:
  8158. movl %eax,%edx
  8159. sarl $31,%edx
  8160. To:
  8161. cltd
  8162. }
  8163. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  8164. RemoveInstruction(hp1);
  8165. taicpu(p).opcode := A_CDQ;
  8166. taicpu(p).opsize := S_NO;
  8167. taicpu(p).clearop(1);
  8168. taicpu(p).clearop(0);
  8169. taicpu(p).ops:=0;
  8170. Result := True;
  8171. end
  8172. else if (cs_opt_size in current_settings.optimizerswitches) and
  8173. (taicpu(p).oper[0]^.reg = NR_EDX) and
  8174. (taicpu(p).oper[1]^.reg = NR_EAX) then
  8175. begin
  8176. { Change:
  8177. movl %edx,%eax
  8178. sarl $31,%edx
  8179. To:
  8180. movl %edx,%eax
  8181. cltd
  8182. Note that this creates a dependency between the two instructions,
  8183. so only perform if optimising for size.
  8184. }
  8185. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  8186. taicpu(hp1).opcode := A_CDQ;
  8187. taicpu(hp1).opsize := S_NO;
  8188. taicpu(hp1).clearop(1);
  8189. taicpu(hp1).clearop(0);
  8190. taicpu(hp1).ops:=0;
  8191. end;
  8192. {$ifndef x86_64}
  8193. end
  8194. { Don't bother if CMOV is supported, because a more optimal
  8195. sequence would have been generated for the Abs() intrinsic }
  8196. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  8197. { the use of %eax also covers the opsize being S_L }
  8198. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  8199. (taicpu(p).oper[0]^.reg = NR_EAX) and
  8200. (taicpu(p).oper[1]^.reg = NR_EDX) and
  8201. GetNextInstruction(hp1, hp2) and
  8202. MatchInstruction(hp2, A_XOR, [S_L]) and
  8203. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  8204. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  8205. GetNextInstruction(hp2, hp3) and
  8206. MatchInstruction(hp3, A_SUB, [S_L]) and
  8207. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  8208. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  8209. begin
  8210. { Change:
  8211. movl %eax,%edx
  8212. sarl $31,%eax
  8213. xorl %eax,%edx
  8214. subl %eax,%edx
  8215. (Instruction that uses %edx)
  8216. (%eax deallocated)
  8217. (%edx deallocated)
  8218. To:
  8219. cltd
  8220. xorl %edx,%eax <-- Note the registers have swapped
  8221. subl %edx,%eax
  8222. (Instruction that uses %eax) <-- %eax rather than %edx
  8223. }
  8224. TransferUsedRegs(TmpUsedRegs);
  8225. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8226. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  8227. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8228. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  8229. begin
  8230. if GetNextInstruction(hp3, hp4) and
  8231. not RegModifiedByInstruction(NR_EDX, hp4) and
  8232. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  8233. begin
  8234. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  8235. taicpu(p).opcode := A_CDQ;
  8236. taicpu(p).clearop(1);
  8237. taicpu(p).clearop(0);
  8238. taicpu(p).ops:=0;
  8239. RemoveInstruction(hp1);
  8240. taicpu(hp2).loadreg(0, NR_EDX);
  8241. taicpu(hp2).loadreg(1, NR_EAX);
  8242. taicpu(hp3).loadreg(0, NR_EDX);
  8243. taicpu(hp3).loadreg(1, NR_EAX);
  8244. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  8245. { Convert references in the following instruction (hp4) from %edx to %eax }
  8246. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  8247. with taicpu(hp4).oper[OperIdx]^ do
  8248. case typ of
  8249. top_reg:
  8250. if getsupreg(reg) = RS_EDX then
  8251. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8252. top_ref:
  8253. begin
  8254. if getsupreg(reg) = RS_EDX then
  8255. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8256. if getsupreg(reg) = RS_EDX then
  8257. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  8258. end;
  8259. else
  8260. ;
  8261. end;
  8262. end;
  8263. end;
  8264. {$else x86_64}
  8265. end;
  8266. end
  8267. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  8268. { the use of %rdx also covers the opsize being S_Q }
  8269. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  8270. begin
  8271. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  8272. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  8273. (taicpu(p).oper[1]^.reg = NR_RDX) then
  8274. begin
  8275. { Change:
  8276. movq %rax,%rdx
  8277. sarq $63,%rdx
  8278. To:
  8279. cqto
  8280. }
  8281. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  8282. RemoveInstruction(hp1);
  8283. taicpu(p).opcode := A_CQO;
  8284. taicpu(p).opsize := S_NO;
  8285. taicpu(p).clearop(1);
  8286. taicpu(p).clearop(0);
  8287. taicpu(p).ops:=0;
  8288. Result := True;
  8289. end
  8290. else if (cs_opt_size in current_settings.optimizerswitches) and
  8291. (taicpu(p).oper[0]^.reg = NR_RDX) and
  8292. (taicpu(p).oper[1]^.reg = NR_RAX) then
  8293. begin
  8294. { Change:
  8295. movq %rdx,%rax
  8296. sarq $63,%rdx
  8297. To:
  8298. movq %rdx,%rax
  8299. cqto
  8300. Note that this creates a dependency between the two instructions,
  8301. so only perform if optimising for size.
  8302. }
  8303. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  8304. taicpu(hp1).opcode := A_CQO;
  8305. taicpu(hp1).opsize := S_NO;
  8306. taicpu(hp1).clearop(1);
  8307. taicpu(hp1).clearop(0);
  8308. taicpu(hp1).ops:=0;
  8309. {$endif x86_64}
  8310. end;
  8311. end;
  8312. end
  8313. else if MatchInstruction(hp1, A_MOV, []) and
  8314. (taicpu(hp1).oper[1]^.typ = top_reg) then
  8315. { Though "GetNextInstruction" could be factored out, along with
  8316. the instructions that depend on hp2, it is an expensive call that
  8317. should be delayed for as long as possible, hence we do cheaper
  8318. checks first that are likely to be False. [Kit] }
  8319. begin
  8320. if (
  8321. (
  8322. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  8323. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  8324. (
  8325. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8326. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  8327. )
  8328. ) or
  8329. (
  8330. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  8331. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  8332. (
  8333. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8334. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  8335. )
  8336. )
  8337. ) and
  8338. GetNextInstruction(hp1, hp2) and
  8339. MatchInstruction(hp2, A_SAR, []) and
  8340. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  8341. begin
  8342. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  8343. begin
  8344. { Change:
  8345. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  8346. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  8347. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  8348. To:
  8349. movl r/m,%eax <- Note the change in register
  8350. cltd
  8351. }
  8352. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  8353. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  8354. taicpu(p).loadreg(1, NR_EAX);
  8355. taicpu(hp1).opcode := A_CDQ;
  8356. taicpu(hp1).clearop(1);
  8357. taicpu(hp1).clearop(0);
  8358. taicpu(hp1).ops:=0;
  8359. RemoveInstruction(hp2);
  8360. (*
  8361. {$ifdef x86_64}
  8362. end
  8363. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  8364. { This code sequence does not get generated - however it might become useful
  8365. if and when 128-bit signed integer types make an appearance, so the code
  8366. is kept here for when it is eventually needed. [Kit] }
  8367. (
  8368. (
  8369. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  8370. (
  8371. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8372. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  8373. )
  8374. ) or
  8375. (
  8376. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  8377. (
  8378. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  8379. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  8380. )
  8381. )
  8382. ) and
  8383. GetNextInstruction(hp1, hp2) and
  8384. MatchInstruction(hp2, A_SAR, [S_Q]) and
  8385. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  8386. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  8387. begin
  8388. { Change:
  8389. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  8390. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  8391. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  8392. To:
  8393. movq r/m,%rax <- Note the change in register
  8394. cqto
  8395. }
  8396. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  8397. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  8398. taicpu(p).loadreg(1, NR_RAX);
  8399. taicpu(hp1).opcode := A_CQO;
  8400. taicpu(hp1).clearop(1);
  8401. taicpu(hp1).clearop(0);
  8402. taicpu(hp1).ops:=0;
  8403. RemoveInstruction(hp2);
  8404. {$endif x86_64}
  8405. *)
  8406. end;
  8407. end;
  8408. {$ifdef x86_64}
  8409. end
  8410. else if (taicpu(p).opsize = S_L) and
  8411. (taicpu(p).oper[1]^.typ = top_reg) and
  8412. (
  8413. MatchInstruction(hp1, A_MOV,[]) and
  8414. (taicpu(hp1).opsize = S_L) and
  8415. (taicpu(hp1).oper[1]^.typ = top_reg)
  8416. ) and (
  8417. GetNextInstruction(hp1, hp2) and
  8418. (tai(hp2).typ=ait_instruction) and
  8419. (taicpu(hp2).opsize = S_Q) and
  8420. (
  8421. (
  8422. MatchInstruction(hp2, A_ADD,[]) and
  8423. (taicpu(hp2).opsize = S_Q) and
  8424. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8425. (
  8426. (
  8427. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8428. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8429. ) or (
  8430. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8431. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8432. )
  8433. )
  8434. ) or (
  8435. MatchInstruction(hp2, A_LEA,[]) and
  8436. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  8437. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  8438. (
  8439. (
  8440. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  8441. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8442. ) or (
  8443. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8444. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  8445. )
  8446. ) and (
  8447. (
  8448. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  8449. ) or (
  8450. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  8451. )
  8452. )
  8453. )
  8454. )
  8455. ) and (
  8456. GetNextInstruction(hp2, hp3) and
  8457. MatchInstruction(hp3, A_SHR,[]) and
  8458. (taicpu(hp3).opsize = S_Q) and
  8459. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  8460. (taicpu(hp3).oper[0]^.val = 1) and
  8461. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  8462. ) then
  8463. begin
  8464. { Change movl x, reg1d movl x, reg1d
  8465. movl y, reg2d movl y, reg2d
  8466. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  8467. shrq $1, reg1q shrq $1, reg1q
  8468. ( reg1d and reg2d can be switched around in the first two instructions )
  8469. To movl x, reg1d
  8470. addl y, reg1d
  8471. rcrl $1, reg1d
  8472. This corresponds to the common expression (x + y) shr 1, where
  8473. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  8474. smaller code, but won't account for x + y causing an overflow). [Kit]
  8475. }
  8476. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8477. { Change first MOV command to have the same register as the final output }
  8478. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  8479. else
  8480. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  8481. { Change second MOV command to an ADD command. This is easier than
  8482. converting the existing command because it means we don't have to
  8483. touch 'y', which might be a complicated reference, and also the
  8484. fact that the third command might either be ADD or LEA. [Kit] }
  8485. taicpu(hp1).opcode := A_ADD;
  8486. { Delete old ADD/LEA instruction }
  8487. RemoveInstruction(hp2);
  8488. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  8489. taicpu(hp3).opcode := A_RCR;
  8490. taicpu(hp3).changeopsize(S_L);
  8491. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  8492. {$endif x86_64}
  8493. end;
  8494. if FuncMov2Func(p, hp1) then
  8495. begin
  8496. Result := True;
  8497. Exit;
  8498. end;
  8499. end;
  8500. {$push}
  8501. {$q-}{$r-}
  8502. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  8503. var
  8504. ThisReg: TRegister;
  8505. MinSize, MaxSize, TryShiftDown, TargetSize: TOpSize;
  8506. TargetSubReg: TSubRegister;
  8507. hp1, hp2: tai;
  8508. RegInUse, RegChanged, p_removed, hp1_removed: Boolean;
  8509. { Store list of found instructions so we don't have to call
  8510. GetNextInstructionUsingReg multiple times }
  8511. InstrList: array of taicpu;
  8512. InstrMax, Index: Integer;
  8513. UpperLimit, SignedUpperLimit, SignedUpperLimitBottom,
  8514. LowerLimit, SignedLowerLimit, SignedLowerLimitBottom,
  8515. TryShiftDownLimit, TryShiftDownSignedLimit, TryShiftDownSignedLimitLower,
  8516. WorkingValue: TCgInt;
  8517. PreMessage: string;
  8518. { Data flow analysis }
  8519. TestValMin, TestValMax, TestValSignedMax: TCgInt;
  8520. BitwiseOnly, OrXorUsed,
  8521. ShiftDownOverflow, UpperSignedOverflow, UpperUnsignedOverflow, LowerSignedOverflow, LowerUnsignedOverflow: Boolean;
  8522. function CheckOverflowConditions: Boolean;
  8523. begin
  8524. Result := True;
  8525. if (TestValSignedMax > SignedUpperLimit) then
  8526. UpperSignedOverflow := True;
  8527. if (TestValSignedMax > SignedLowerLimit) or (TestValSignedMax < SignedLowerLimitBottom) then
  8528. LowerSignedOverflow := True;
  8529. if (TestValMin > LowerLimit) or (TestValMax > LowerLimit) then
  8530. LowerUnsignedOverflow := True;
  8531. if (TestValMin > UpperLimit) or (TestValMax > UpperLimit) or (TestValSignedMax > UpperLimit) or
  8532. (TestValMin < SignedUpperLimitBottom) or (TestValMax < SignedUpperLimitBottom) or (TestValSignedMax < SignedUpperLimitBottom) then
  8533. begin
  8534. { Absolute overflow }
  8535. Result := False;
  8536. Exit;
  8537. end;
  8538. if not ShiftDownOverflow and (TryShiftDown <> S_NO) and
  8539. ((TestValMin > TryShiftDownLimit) or (TestValMax > TryShiftDownLimit)) then
  8540. ShiftDownOverflow := True;
  8541. if (TestValMin < 0) or (TestValMax < 0) then
  8542. begin
  8543. LowerUnsignedOverflow := True;
  8544. UpperUnsignedOverflow := True;
  8545. end;
  8546. end;
  8547. function AdjustInitialLoadAndSize: Boolean;
  8548. begin
  8549. Result := False;
  8550. if not p_removed then
  8551. begin
  8552. if TargetSize = MinSize then
  8553. begin
  8554. { Convert the input MOVZX to a MOV }
  8555. if (taicpu(p).oper[0]^.typ = top_reg) and
  8556. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8557. begin
  8558. { Or remove it completely! }
  8559. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  8560. RemoveCurrentP(p);
  8561. p_removed := True;
  8562. end
  8563. else
  8564. begin
  8565. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  8566. taicpu(p).opcode := A_MOV;
  8567. taicpu(p).oper[1]^.reg := ThisReg;
  8568. taicpu(p).opsize := TargetSize;
  8569. end;
  8570. Result := True;
  8571. end
  8572. else if TargetSize <> MaxSize then
  8573. begin
  8574. case MaxSize of
  8575. S_L:
  8576. if TargetSize = S_W then
  8577. begin
  8578. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  8579. taicpu(p).opsize := S_BW;
  8580. taicpu(p).oper[1]^.reg := ThisReg;
  8581. Result := True;
  8582. end
  8583. else
  8584. InternalError(2020112341);
  8585. S_W:
  8586. if TargetSize = S_L then
  8587. begin
  8588. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  8589. taicpu(p).opsize := S_BL;
  8590. taicpu(p).oper[1]^.reg := ThisReg;
  8591. Result := True;
  8592. end
  8593. else
  8594. InternalError(2020112342);
  8595. else
  8596. ;
  8597. end;
  8598. end
  8599. else if not hp1_removed and not RegInUse then
  8600. begin
  8601. { If we have something like:
  8602. movzbl (oper),%regd
  8603. add x, %regd
  8604. movzbl %regb, %regd
  8605. We can reduce the register size to the input of the final
  8606. movzbl instruction. Overflows won't have any effect.
  8607. }
  8608. if (taicpu(p).opsize in [S_BW, S_BL]) and
  8609. (taicpu(hp1).opsize in [S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8610. begin
  8611. TargetSize := S_B;
  8612. setsubreg(ThisReg, R_SUBL);
  8613. Result := True;
  8614. end
  8615. else if (taicpu(p).opsize = S_WL) and
  8616. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64}, S_BQ{$endif x86_64}]) then
  8617. begin
  8618. TargetSize := S_W;
  8619. setsubreg(ThisReg, R_SUBW);
  8620. Result := True;
  8621. end;
  8622. if Result then
  8623. begin
  8624. { Convert the input MOVZX to a MOV }
  8625. if (taicpu(p).oper[0]^.typ = top_reg) and
  8626. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  8627. begin
  8628. { Or remove it completely! }
  8629. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  8630. RemoveCurrentP(p);
  8631. p_removed := True;
  8632. end
  8633. else
  8634. begin
  8635. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  8636. taicpu(p).opcode := A_MOV;
  8637. taicpu(p).oper[1]^.reg := ThisReg;
  8638. taicpu(p).opsize := TargetSize;
  8639. end;
  8640. end;
  8641. end;
  8642. end;
  8643. end;
  8644. procedure AdjustFinalLoad;
  8645. begin
  8646. if not LowerUnsignedOverflow then
  8647. begin
  8648. if ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  8649. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  8650. begin
  8651. { Convert the output MOVZX to a MOV }
  8652. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8653. begin
  8654. { Or remove it completely! }
  8655. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  8656. { Be careful; if p = hp1 and p was also removed, p
  8657. will become a dangling pointer }
  8658. if p = hp1 then
  8659. begin
  8660. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8661. p_removed := True;
  8662. end
  8663. else
  8664. RemoveInstruction(hp1);
  8665. hp1_removed := True;
  8666. end
  8667. else
  8668. begin
  8669. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  8670. taicpu(hp1).opcode := A_MOV;
  8671. taicpu(hp1).oper[0]^.reg := ThisReg;
  8672. taicpu(hp1).opsize := TargetSize;
  8673. end;
  8674. end
  8675. else if (TargetSize = S_B) and (MaxSize = S_W) and (taicpu(hp1).opsize = S_WL) then
  8676. begin
  8677. { Need to change the size of the output }
  8678. DebugMsg(SPeepholeOptimization + 'movzwl2movzbl 2', hp1);
  8679. taicpu(hp1).oper[0]^.reg := ThisReg;
  8680. taicpu(hp1).opsize := S_BL;
  8681. end;
  8682. end;
  8683. end;
  8684. function CompressInstructions: Boolean;
  8685. var
  8686. LocalIndex: Integer;
  8687. begin
  8688. Result := False;
  8689. { The objective here is to try to find a combination that
  8690. removes one of the MOV/Z instructions. }
  8691. if (
  8692. (taicpu(p).oper[0]^.typ <> top_reg) or
  8693. not SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg)
  8694. ) and
  8695. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8696. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8697. begin
  8698. { Make a preference to remove the second MOVZX instruction }
  8699. case taicpu(hp1).opsize of
  8700. S_BL, S_WL:
  8701. begin
  8702. TargetSize := S_L;
  8703. TargetSubReg := R_SUBD;
  8704. end;
  8705. S_BW:
  8706. begin
  8707. TargetSize := S_W;
  8708. TargetSubReg := R_SUBW;
  8709. end;
  8710. else
  8711. InternalError(2020112302);
  8712. end;
  8713. end
  8714. else
  8715. begin
  8716. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  8717. begin
  8718. { Exceeded lower bound but not upper bound }
  8719. TargetSize := MaxSize;
  8720. end
  8721. else if not LowerUnsignedOverflow then
  8722. begin
  8723. { Size didn't exceed lower bound }
  8724. TargetSize := MinSize;
  8725. end
  8726. else
  8727. Exit;
  8728. end;
  8729. case TargetSize of
  8730. S_B:
  8731. TargetSubReg := R_SUBL;
  8732. S_W:
  8733. TargetSubReg := R_SUBW;
  8734. S_L:
  8735. TargetSubReg := R_SUBD;
  8736. else
  8737. InternalError(2020112350);
  8738. end;
  8739. { Update the register to its new size }
  8740. setsubreg(ThisReg, TargetSubReg);
  8741. RegInUse := False;
  8742. if not SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  8743. begin
  8744. { Check to see if the active register is used afterwards;
  8745. if not, we can change it and make a saving. }
  8746. TransferUsedRegs(TmpUsedRegs);
  8747. { The target register may be marked as in use to cross
  8748. a jump to a distant label, so exclude it }
  8749. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  8750. hp2 := p;
  8751. repeat
  8752. { Explicitly check for the excluded register (don't include the first
  8753. instruction as it may be reading from here }
  8754. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  8755. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  8756. begin
  8757. RegInUse := True;
  8758. Break;
  8759. end;
  8760. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  8761. if not GetNextInstruction(hp2, hp2) then
  8762. InternalError(2020112340);
  8763. until (hp2 = hp1);
  8764. if not RegInUse and RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  8765. { We might still be able to get away with this }
  8766. RegInUse := not
  8767. (
  8768. GetNextInstructionUsingReg(hp1, hp2, ThisReg) and
  8769. (hp2.typ = ait_instruction) and
  8770. (
  8771. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8772. instruction that doesn't actually contain ThisReg }
  8773. (cs_opt_level3 in current_settings.optimizerswitches) or
  8774. RegInInstruction(ThisReg, hp2)
  8775. ) and
  8776. RegLoadedWithNewValue(ThisReg, hp2)
  8777. );
  8778. if not RegInUse then
  8779. begin
  8780. { Force the register size to the same as this instruction so it can be removed}
  8781. if (taicpu(hp1).opsize in [S_L, S_BL, S_WL]) then
  8782. begin
  8783. TargetSize := S_L;
  8784. TargetSubReg := R_SUBD;
  8785. end
  8786. else if (taicpu(hp1).opsize in [S_W, S_BW]) then
  8787. begin
  8788. TargetSize := S_W;
  8789. TargetSubReg := R_SUBW;
  8790. end;
  8791. ThisReg := taicpu(hp1).oper[1]^.reg;
  8792. setsubreg(ThisReg, TargetSubReg);
  8793. RegChanged := True;
  8794. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(ThisReg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  8795. TransferUsedRegs(TmpUsedRegs);
  8796. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  8797. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  8798. if p = hp1 then
  8799. begin
  8800. RemoveCurrentp(p); { p = hp1 and will then become the next instruction }
  8801. p_removed := True;
  8802. end
  8803. else
  8804. RemoveInstruction(hp1);
  8805. hp1_removed := True;
  8806. { Instruction will become "mov %reg,%reg" }
  8807. if not p_removed and (taicpu(p).opcode = A_MOV) and
  8808. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  8809. begin
  8810. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  8811. RemoveCurrentP(p);
  8812. p_removed := True;
  8813. end
  8814. else
  8815. taicpu(p).oper[1]^.reg := ThisReg;
  8816. Result := True;
  8817. end
  8818. else
  8819. begin
  8820. if TargetSize <> MaxSize then
  8821. begin
  8822. { Since the register is in use, we have to force it to
  8823. MaxSize otherwise part of it may become undefined later on }
  8824. TargetSize := MaxSize;
  8825. case TargetSize of
  8826. S_B:
  8827. TargetSubReg := R_SUBL;
  8828. S_W:
  8829. TargetSubReg := R_SUBW;
  8830. S_L:
  8831. TargetSubReg := R_SUBD;
  8832. else
  8833. InternalError(2020112351);
  8834. end;
  8835. setsubreg(ThisReg, TargetSubReg);
  8836. end;
  8837. AdjustFinalLoad;
  8838. end;
  8839. end
  8840. else
  8841. AdjustFinalLoad;
  8842. Result := AdjustInitialLoadAndSize or Result;
  8843. { Now go through every instruction we found and change the
  8844. size. If TargetSize = MaxSize, then almost no changes are
  8845. needed and Result can remain False if it hasn't been set
  8846. yet.
  8847. If RegChanged is True, then the register requires changing
  8848. and so the point about TargetSize = MaxSize doesn't apply. }
  8849. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  8850. begin
  8851. for LocalIndex := 0 to InstrMax do
  8852. begin
  8853. { If p_removed is true, then the original MOV/Z was removed
  8854. and removing the AND instruction may not be safe if it
  8855. appears first }
  8856. if (InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.typ <> top_reg) then
  8857. InternalError(2020112310);
  8858. if InstrList[LocalIndex].oper[0]^.typ = top_reg then
  8859. InstrList[LocalIndex].oper[0]^.reg := ThisReg;
  8860. InstrList[LocalIndex].oper[InstrList[LocalIndex].ops - 1]^.reg := ThisReg;
  8861. InstrList[LocalIndex].opsize := TargetSize;
  8862. end;
  8863. Result := True;
  8864. end;
  8865. end;
  8866. begin
  8867. Result := False;
  8868. p_removed := False;
  8869. hp1_removed := False;
  8870. ThisReg := taicpu(p).oper[1]^.reg;
  8871. { Check for:
  8872. movs/z ###,%ecx (or %cx or %rcx)
  8873. ...
  8874. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8875. (dealloc %ecx)
  8876. Change to:
  8877. mov ###,%cl (if ### = %cl, then remove completely)
  8878. ...
  8879. shl/shr/sar/rcl/rcr/ror/rol %cl,###
  8880. }
  8881. if (getsupreg(ThisReg) = RS_ECX) and
  8882. GetNextInstructionUsingReg(p, hp1, NR_ECX) and
  8883. (hp1.typ = ait_instruction) and
  8884. (
  8885. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  8886. instruction that doesn't actually contain ECX }
  8887. (cs_opt_level3 in current_settings.optimizerswitches) or
  8888. RegInInstruction(NR_ECX, hp1) or
  8889. (
  8890. { It's common for the shift/rotate's read/write register to be
  8891. initialised in between, so under -O2 and under, search ahead
  8892. one more instruction
  8893. }
  8894. GetNextInstruction(hp1, hp1) and
  8895. (hp1.typ = ait_instruction) and
  8896. RegInInstruction(NR_ECX, hp1)
  8897. )
  8898. ) and
  8899. MatchInstruction(hp1, [A_SHL, A_SHR, A_SAR, A_ROR, A_ROL, A_RCR, A_RCL], []) and
  8900. (taicpu(hp1).oper[0]^.typ = top_reg) { This is enough to determine that it's %cl } then
  8901. begin
  8902. TransferUsedRegs(TmpUsedRegs);
  8903. hp2 := p;
  8904. repeat
  8905. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8906. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8907. if not RegUsedAfterInstruction(NR_CL, hp1, TmpUsedRegs) then
  8908. begin
  8909. case taicpu(p).opsize of
  8910. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8911. if MatchOperand(taicpu(p).oper[0]^, NR_CL) then
  8912. begin
  8913. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3a', p);
  8914. RemoveCurrentP(p);
  8915. end
  8916. else
  8917. begin
  8918. taicpu(p).opcode := A_MOV;
  8919. taicpu(p).opsize := S_B;
  8920. taicpu(p).oper[1]^.reg := NR_CL;
  8921. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 1', p);
  8922. end;
  8923. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8924. if MatchOperand(taicpu(p).oper[0]^, NR_CX) then
  8925. begin
  8926. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3b', p);
  8927. RemoveCurrentP(p);
  8928. end
  8929. else
  8930. begin
  8931. taicpu(p).opcode := A_MOV;
  8932. taicpu(p).opsize := S_W;
  8933. taicpu(p).oper[1]^.reg := NR_CX;
  8934. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 2', p);
  8935. end;
  8936. {$ifdef x86_64}
  8937. S_LQ:
  8938. if MatchOperand(taicpu(p).oper[0]^, NR_ECX) then
  8939. begin
  8940. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 3c', p);
  8941. RemoveCurrentP(p);
  8942. end
  8943. else
  8944. begin
  8945. taicpu(p).opcode := A_MOV;
  8946. taicpu(p).opsize := S_L;
  8947. taicpu(p).oper[1]^.reg := NR_ECX;
  8948. DebugMsg(SPeepholeOptimization + 'MovxOp2MovOp 3', p);
  8949. end;
  8950. {$endif x86_64}
  8951. else
  8952. InternalError(2021120401);
  8953. end;
  8954. Result := True;
  8955. Exit;
  8956. end;
  8957. end;
  8958. { This is anything but quick! }
  8959. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  8960. Exit;
  8961. SetLength(InstrList, 0);
  8962. InstrMax := -1;
  8963. case taicpu(p).opsize of
  8964. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8965. begin
  8966. {$if defined(i386) or defined(i8086)}
  8967. { If the target size is 8-bit, make sure we can actually encode it }
  8968. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  8969. Exit;
  8970. {$endif i386 or i8086}
  8971. LowerLimit := $FF;
  8972. SignedLowerLimit := $7F;
  8973. SignedLowerLimitBottom := -128;
  8974. MinSize := S_B;
  8975. if taicpu(p).opsize = S_BW then
  8976. begin
  8977. MaxSize := S_W;
  8978. UpperLimit := $FFFF;
  8979. SignedUpperLimit := $7FFF;
  8980. SignedUpperLimitBottom := -32768;
  8981. end
  8982. else
  8983. begin
  8984. { Keep at a 32-bit limit for BQ as well since one can't really optimise otherwise }
  8985. MaxSize := S_L;
  8986. UpperLimit := $FFFFFFFF;
  8987. SignedUpperLimit := $7FFFFFFF;
  8988. SignedUpperLimitBottom := -2147483648;
  8989. end;
  8990. end;
  8991. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8992. begin
  8993. { Keep at a 32-bit limit for WQ as well since one can't really optimise otherwise }
  8994. LowerLimit := $FFFF;
  8995. SignedLowerLimit := $7FFF;
  8996. SignedLowerLimitBottom := -32768;
  8997. UpperLimit := $FFFFFFFF;
  8998. SignedUpperLimit := $7FFFFFFF;
  8999. SignedUpperLimitBottom := -2147483648;
  9000. MinSize := S_W;
  9001. MaxSize := S_L;
  9002. end;
  9003. {$ifdef x86_64}
  9004. S_LQ:
  9005. begin
  9006. { Both the lower and upper limits are set to 32-bit. If a limit
  9007. is breached, then optimisation is impossible }
  9008. LowerLimit := $FFFFFFFF;
  9009. SignedLowerLimit := $7FFFFFFF;
  9010. SignedLowerLimitBottom := -2147483648;
  9011. UpperLimit := $FFFFFFFF;
  9012. SignedUpperLimit := $7FFFFFFF;
  9013. SignedUpperLimitBottom := -2147483648;
  9014. MinSize := S_L;
  9015. MaxSize := S_L;
  9016. end;
  9017. {$endif x86_64}
  9018. else
  9019. InternalError(2020112301);
  9020. end;
  9021. TestValMin := 0;
  9022. TestValMax := LowerLimit;
  9023. TestValSignedMax := SignedLowerLimit;
  9024. TryShiftDownLimit := LowerLimit;
  9025. TryShiftDown := S_NO;
  9026. ShiftDownOverflow := False;
  9027. RegChanged := False;
  9028. BitwiseOnly := True;
  9029. OrXorUsed := False;
  9030. UpperSignedOverflow := False;
  9031. LowerSignedOverflow := False;
  9032. UpperUnsignedOverflow := False;
  9033. LowerUnsignedOverflow := False;
  9034. hp1 := p;
  9035. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  9036. (hp1.typ = ait_instruction) and
  9037. (
  9038. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  9039. instruction that doesn't actually contain ThisReg }
  9040. (cs_opt_level3 in current_settings.optimizerswitches) or
  9041. { This allows this Movx optimisation to work through the SETcc instructions
  9042. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9043. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9044. skip over these SETcc instructions). }
  9045. (taicpu(hp1).opcode = A_SETcc) or
  9046. RegInInstruction(ThisReg, hp1)
  9047. ) do
  9048. begin
  9049. case taicpu(hp1).opcode of
  9050. A_INC,A_DEC:
  9051. begin
  9052. { Has to be an exact match on the register }
  9053. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  9054. Break;
  9055. if taicpu(hp1).opcode = A_INC then
  9056. begin
  9057. Inc(TestValMin);
  9058. Inc(TestValMax);
  9059. Inc(TestValSignedMax);
  9060. end
  9061. else
  9062. begin
  9063. Dec(TestValMin);
  9064. Dec(TestValMax);
  9065. Dec(TestValSignedMax);
  9066. end;
  9067. end;
  9068. A_TEST, A_CMP:
  9069. begin
  9070. if (
  9071. { Too high a risk of non-linear behaviour that breaks DFA
  9072. here, unless it's cmp $0,%reg, which is equivalent to
  9073. test %reg,%reg }
  9074. OrXorUsed and
  9075. (taicpu(hp1).opcode = A_CMP) and
  9076. not Matchoperand(taicpu(hp1).oper[0]^, 0)
  9077. ) or
  9078. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9079. { Has to be an exact match on the register }
  9080. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9081. (
  9082. { Permit "test %reg,%reg" }
  9083. (taicpu(hp1).opcode = A_TEST) and
  9084. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9085. (taicpu(hp1).oper[0]^.reg <> ThisReg)
  9086. ) or
  9087. (taicpu(hp1).oper[0]^.typ <> top_const) or
  9088. { Make sure the comparison value is not smaller than the
  9089. smallest allowed signed value for the minimum size (e.g.
  9090. -128 for 8-bit) }
  9091. not (
  9092. ((taicpu(hp1).oper[0]^.val and LowerLimit) = taicpu(hp1).oper[0]^.val) or
  9093. { Is it in the negative range? }
  9094. (
  9095. (taicpu(hp1).oper[0]^.val < 0) and
  9096. (taicpu(hp1).oper[0]^.val >= SignedLowerLimitBottom)
  9097. )
  9098. ) then
  9099. Break;
  9100. { Check to see if the active register is used afterwards }
  9101. TransferUsedRegs(TmpUsedRegs);
  9102. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  9103. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  9104. begin
  9105. { Make sure the comparison or any previous instructions
  9106. hasn't pushed the test values outside of the range of
  9107. MinSize }
  9108. if LowerUnsignedOverflow and not UpperUnsignedOverflow then
  9109. begin
  9110. { Exceeded lower bound but not upper bound }
  9111. Exit;
  9112. end
  9113. else if not LowerSignedOverflow or not LowerUnsignedOverflow then
  9114. begin
  9115. { Size didn't exceed lower bound }
  9116. TargetSize := MinSize;
  9117. end
  9118. else
  9119. Break;
  9120. case TargetSize of
  9121. S_B:
  9122. TargetSubReg := R_SUBL;
  9123. S_W:
  9124. TargetSubReg := R_SUBW;
  9125. S_L:
  9126. TargetSubReg := R_SUBD;
  9127. else
  9128. InternalError(2021051002);
  9129. end;
  9130. if TargetSize <> MaxSize then
  9131. begin
  9132. { Update the register to its new size }
  9133. setsubreg(ThisReg, TargetSubReg);
  9134. DebugMsg(SPeepholeOptimization + 'CMP instruction resized thanks to register size optimisation (see MOV/Z assignment above)', hp1);
  9135. taicpu(hp1).oper[1]^.reg := ThisReg;
  9136. taicpu(hp1).opsize := TargetSize;
  9137. { Convert the input MOVZX to a MOV if necessary }
  9138. AdjustInitialLoadAndSize;
  9139. if (InstrMax >= 0) then
  9140. begin
  9141. for Index := 0 to InstrMax do
  9142. begin
  9143. { If p_removed is true, then the original MOV/Z was removed
  9144. and removing the AND instruction may not be safe if it
  9145. appears first }
  9146. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  9147. InternalError(2020112311);
  9148. if InstrList[Index].oper[0]^.typ = top_reg then
  9149. InstrList[Index].oper[0]^.reg := ThisReg;
  9150. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  9151. InstrList[Index].opsize := MinSize;
  9152. end;
  9153. end;
  9154. Result := True;
  9155. end;
  9156. Exit;
  9157. end;
  9158. end;
  9159. A_SETcc:
  9160. begin
  9161. { This allows this Movx optimisation to work through the SETcc instructions
  9162. inserted by the 'CMP/JE/CMP/@Lbl/SETE -> CMP/SETE/CMP/SETE/OR'
  9163. optimisation on -O1 and -O2 (on -O3, GetNextInstructionUsingReg will
  9164. skip over these SETcc instructions). }
  9165. if (cs_opt_level3 in current_settings.optimizerswitches) or
  9166. { Of course, break out if the current register is used }
  9167. RegInOp(ThisReg, taicpu(hp1).oper[0]^) then
  9168. Break
  9169. else
  9170. { We must use Continue so the instruction doesn't get added
  9171. to InstrList }
  9172. Continue;
  9173. end;
  9174. A_ADD,A_SUB,A_AND,A_OR,A_XOR,A_SHL,A_SHR,A_SAR:
  9175. begin
  9176. if
  9177. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  9178. { Has to be an exact match on the register }
  9179. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  9180. (
  9181. (
  9182. (taicpu(hp1).oper[0]^.typ = top_const) and
  9183. (
  9184. (
  9185. (taicpu(hp1).opcode = A_SHL) and
  9186. (
  9187. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  9188. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  9189. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  9190. )
  9191. ) or (
  9192. (taicpu(hp1).opcode <> A_SHL) and
  9193. (
  9194. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9195. { Is it in the negative range? }
  9196. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  9197. )
  9198. )
  9199. )
  9200. ) or (
  9201. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  9202. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  9203. )
  9204. ) then
  9205. Break;
  9206. { Only process OR and XOR if there are only bitwise operations,
  9207. since otherwise they can too easily fool the data flow
  9208. analysis (they can cause non-linear behaviour) }
  9209. case taicpu(hp1).opcode of
  9210. A_ADD:
  9211. begin
  9212. if OrXorUsed then
  9213. { Too high a risk of non-linear behaviour that breaks DFA here }
  9214. Break
  9215. else
  9216. BitwiseOnly := False;
  9217. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9218. begin
  9219. TestValMin := TestValMin * 2;
  9220. TestValMax := TestValMax * 2;
  9221. TestValSignedMax := TestValSignedMax * 2;
  9222. end
  9223. else
  9224. begin
  9225. WorkingValue := taicpu(hp1).oper[0]^.val;
  9226. TestValMin := TestValMin + WorkingValue;
  9227. TestValMax := TestValMax + WorkingValue;
  9228. TestValSignedMax := TestValSignedMax + WorkingValue;
  9229. end;
  9230. end;
  9231. A_SUB:
  9232. begin
  9233. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9234. begin
  9235. TestValMin := 0;
  9236. TestValMax := 0;
  9237. TestValSignedMax := 0;
  9238. end
  9239. else
  9240. begin
  9241. if OrXorUsed then
  9242. { Too high a risk of non-linear behaviour that breaks DFA here }
  9243. Break
  9244. else
  9245. BitwiseOnly := False;
  9246. WorkingValue := taicpu(hp1).oper[0]^.val;
  9247. TestValMin := TestValMin - WorkingValue;
  9248. TestValMax := TestValMax - WorkingValue;
  9249. TestValSignedMax := TestValSignedMax - WorkingValue;
  9250. end;
  9251. end;
  9252. A_AND:
  9253. if (taicpu(hp1).oper[0]^.typ = top_const) then
  9254. begin
  9255. { we might be able to go smaller if AND appears first }
  9256. if InstrMax = -1 then
  9257. case MinSize of
  9258. S_B:
  9259. ;
  9260. S_W:
  9261. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9262. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9263. begin
  9264. TryShiftDown := S_B;
  9265. TryShiftDownLimit := $FF;
  9266. end;
  9267. S_L:
  9268. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  9269. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  9270. begin
  9271. TryShiftDown := S_B;
  9272. TryShiftDownLimit := $FF;
  9273. end
  9274. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  9275. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  9276. begin
  9277. TryShiftDown := S_W;
  9278. TryShiftDownLimit := $FFFF;
  9279. end;
  9280. else
  9281. InternalError(2020112320);
  9282. end;
  9283. WorkingValue := taicpu(hp1).oper[0]^.val;
  9284. TestValMin := TestValMin and WorkingValue;
  9285. TestValMax := TestValMax and WorkingValue;
  9286. TestValSignedMax := TestValSignedMax and WorkingValue;
  9287. end;
  9288. A_OR:
  9289. begin
  9290. if not BitwiseOnly then
  9291. Break;
  9292. OrXorUsed := True;
  9293. WorkingValue := taicpu(hp1).oper[0]^.val;
  9294. TestValMin := TestValMin or WorkingValue;
  9295. TestValMax := TestValMax or WorkingValue;
  9296. TestValSignedMax := TestValSignedMax or WorkingValue;
  9297. end;
  9298. A_XOR:
  9299. begin
  9300. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  9301. begin
  9302. TestValMin := 0;
  9303. TestValMax := 0;
  9304. TestValSignedMax := 0;
  9305. end
  9306. else
  9307. begin
  9308. if not BitwiseOnly then
  9309. Break;
  9310. OrXorUsed := True;
  9311. WorkingValue := taicpu(hp1).oper[0]^.val;
  9312. TestValMin := TestValMin xor WorkingValue;
  9313. TestValMax := TestValMax xor WorkingValue;
  9314. TestValSignedMax := TestValSignedMax xor WorkingValue;
  9315. end;
  9316. end;
  9317. A_SHL:
  9318. begin
  9319. BitwiseOnly := False;
  9320. WorkingValue := taicpu(hp1).oper[0]^.val;
  9321. TestValMin := TestValMin shl WorkingValue;
  9322. TestValMax := TestValMax shl WorkingValue;
  9323. TestValSignedMax := TestValSignedMax shl WorkingValue;
  9324. end;
  9325. A_SHR,
  9326. { The first instruction was MOVZX, so the value won't be negative }
  9327. A_SAR:
  9328. begin
  9329. if InstrMax <> -1 then
  9330. BitwiseOnly := False
  9331. else
  9332. { we might be able to go smaller if SHR appears first }
  9333. case MinSize of
  9334. S_B:
  9335. ;
  9336. S_W:
  9337. if (taicpu(hp1).oper[0]^.val >= 8) then
  9338. begin
  9339. TryShiftDown := S_B;
  9340. TryShiftDownLimit := $FF;
  9341. TryShiftDownSignedLimit := $7F;
  9342. TryShiftDownSignedLimitLower := -128;
  9343. end;
  9344. S_L:
  9345. if (taicpu(hp1).oper[0]^.val >= 24) then
  9346. begin
  9347. TryShiftDown := S_B;
  9348. TryShiftDownLimit := $FF;
  9349. TryShiftDownSignedLimit := $7F;
  9350. TryShiftDownSignedLimitLower := -128;
  9351. end
  9352. else if (taicpu(hp1).oper[0]^.val >= 16) then
  9353. begin
  9354. TryShiftDown := S_W;
  9355. TryShiftDownLimit := $FFFF;
  9356. TryShiftDownSignedLimit := $7FFF;
  9357. TryShiftDownSignedLimitLower := -32768;
  9358. end;
  9359. else
  9360. InternalError(2020112321);
  9361. end;
  9362. WorkingValue := taicpu(hp1).oper[0]^.val;
  9363. if taicpu(hp1).opcode = A_SAR then
  9364. begin
  9365. TestValMin := SarInt64(TestValMin, WorkingValue);
  9366. TestValMax := SarInt64(TestValMax, WorkingValue);
  9367. TestValSignedMax := SarInt64(TestValSignedMax, WorkingValue);
  9368. end
  9369. else
  9370. begin
  9371. TestValMin := TestValMin shr WorkingValue;
  9372. TestValMax := TestValMax shr WorkingValue;
  9373. TestValSignedMax := TestValSignedMax shr WorkingValue;
  9374. end;
  9375. end;
  9376. else
  9377. InternalError(2020112303);
  9378. end;
  9379. end;
  9380. (*
  9381. A_IMUL:
  9382. case taicpu(hp1).ops of
  9383. 2:
  9384. begin
  9385. if not MatchOpType(hp1, top_reg, top_reg) or
  9386. { Has to be an exact match on the register }
  9387. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  9388. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  9389. Break;
  9390. TestValMin := TestValMin * TestValMin;
  9391. TestValMax := TestValMax * TestValMax;
  9392. TestValSignedMax := TestValSignedMax * TestValMax;
  9393. end;
  9394. 3:
  9395. begin
  9396. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9397. { Has to be an exact match on the register }
  9398. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9399. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9400. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9401. { Is it in the negative range? }
  9402. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9403. Break;
  9404. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  9405. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  9406. TestValSignedMax := TestValSignedMax * taicpu(hp1).oper[0]^.val;
  9407. end;
  9408. else
  9409. Break;
  9410. end;
  9411. A_IDIV:
  9412. case taicpu(hp1).ops of
  9413. 3:
  9414. begin
  9415. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  9416. { Has to be an exact match on the register }
  9417. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  9418. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  9419. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  9420. { Is it in the negative range? }
  9421. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  9422. Break;
  9423. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  9424. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  9425. TestValSignedMax := TestValSignedMax div taicpu(hp1).oper[0]^.val;
  9426. end;
  9427. else
  9428. Break;
  9429. end;
  9430. *)
  9431. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  9432. begin
  9433. { If there are no instructions in between, then we might be able to make a saving }
  9434. if UpperSignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) or (taicpu(hp1).oper[0]^.reg <> ThisReg) then
  9435. Break;
  9436. { We have something like:
  9437. movzbw %dl,%dx
  9438. ...
  9439. movswl %dx,%edx
  9440. Change the latter to a zero-extension then enter the
  9441. A_MOVZX case branch.
  9442. }
  9443. {$ifdef x86_64}
  9444. if (taicpu(hp1).opsize = S_LQ) and SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9445. begin
  9446. { this becomes a zero extension from 32-bit to 64-bit, but
  9447. the upper 32 bits are already zero, so just delete the
  9448. instruction }
  9449. DebugMsg(SPeepholeOptimization + 'MovzMovsxd2MovzNop', hp1);
  9450. RemoveInstruction(hp1);
  9451. Result := True;
  9452. Exit;
  9453. end
  9454. else
  9455. {$endif x86_64}
  9456. begin
  9457. DebugMsg(SPeepholeOptimization + 'MovzMovs2MovzMovz', hp1);
  9458. taicpu(hp1).opcode := A_MOVZX;
  9459. {$ifdef x86_64}
  9460. case taicpu(hp1).opsize of
  9461. S_BQ:
  9462. begin
  9463. taicpu(hp1).opsize := S_BL;
  9464. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9465. end;
  9466. S_WQ:
  9467. begin
  9468. taicpu(hp1).opsize := S_WL;
  9469. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9470. end;
  9471. S_LQ:
  9472. begin
  9473. taicpu(hp1).opcode := A_MOV;
  9474. taicpu(hp1).opsize := S_L;
  9475. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  9476. { In this instance, we need to break out because the
  9477. instruction is no longer MOVZX or MOVSXD }
  9478. Result := True;
  9479. Exit;
  9480. end;
  9481. else
  9482. ;
  9483. end;
  9484. {$endif x86_64}
  9485. Result := CompressInstructions;
  9486. Exit;
  9487. end;
  9488. end;
  9489. A_MOVZX:
  9490. begin
  9491. if UpperUnsignedOverflow or (taicpu(hp1).oper[0]^.typ <> top_reg) then
  9492. Break;
  9493. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  9494. begin
  9495. if (InstrMax = -1) and
  9496. { Will return false if the second parameter isn't ThisReg
  9497. (can happen on -O2 and under) }
  9498. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  9499. begin
  9500. { The two MOVZX instructions are adjacent, so remove the first one }
  9501. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  9502. RemoveCurrentP(p);
  9503. Result := True;
  9504. Exit;
  9505. end;
  9506. Break;
  9507. end;
  9508. Result := CompressInstructions;
  9509. Exit;
  9510. end;
  9511. else
  9512. { This includes ADC, SBB and IDIV }
  9513. Break;
  9514. end;
  9515. if not CheckOverflowConditions then
  9516. Break;
  9517. { Contains highest index (so instruction count - 1) }
  9518. Inc(InstrMax);
  9519. if InstrMax > High(InstrList) then
  9520. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9521. InstrList[InstrMax] := taicpu(hp1);
  9522. end;
  9523. end;
  9524. {$pop}
  9525. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  9526. var
  9527. hp1 : tai;
  9528. begin
  9529. Result:=false;
  9530. if (taicpu(p).ops >= 2) and
  9531. ((taicpu(p).oper[0]^.typ = top_const) or
  9532. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  9533. (taicpu(p).oper[1]^.typ = top_reg) and
  9534. ((taicpu(p).ops = 2) or
  9535. ((taicpu(p).oper[2]^.typ = top_reg) and
  9536. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  9537. GetLastInstruction(p,hp1) and
  9538. MatchInstruction(hp1,A_MOV,[]) and
  9539. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9540. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  9541. begin
  9542. TransferUsedRegs(TmpUsedRegs);
  9543. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  9544. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  9545. { change
  9546. mov reg1,reg2
  9547. imul y,reg2 to imul y,reg1,reg2 }
  9548. begin
  9549. taicpu(p).ops := 3;
  9550. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  9551. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  9552. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  9553. RemoveInstruction(hp1);
  9554. result:=true;
  9555. end;
  9556. end;
  9557. end;
  9558. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  9559. var
  9560. ThisLabel: TAsmLabel;
  9561. begin
  9562. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  9563. ThisLabel.decrefs;
  9564. taicpu(p).condition := C_None;
  9565. taicpu(p).opcode := A_RET;
  9566. taicpu(p).is_jmp := false;
  9567. taicpu(p).ops := taicpu(ret_p).ops;
  9568. case taicpu(ret_p).ops of
  9569. 0:
  9570. taicpu(p).clearop(0);
  9571. 1:
  9572. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  9573. else
  9574. internalerror(2016041301);
  9575. end;
  9576. { If the original label is now dead, it might turn out that the label
  9577. immediately follows p. As a result, everything beyond it, which will
  9578. be just some final register configuration and a RET instruction, is
  9579. now dead code. [Kit] }
  9580. { NOTE: This is much faster than introducing a OptPass2RET routine and
  9581. running RemoveDeadCodeAfterJump for each RET instruction, because
  9582. this optimisation rarely happens and most RETs appear at the end of
  9583. routines where there is nothing that can be stripped. [Kit] }
  9584. if not ThisLabel.is_used then
  9585. RemoveDeadCodeAfterJump(p);
  9586. end;
  9587. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  9588. var
  9589. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  9590. Unconditional, PotentialModified: Boolean;
  9591. OperPtr: POper;
  9592. NewRef: TReference;
  9593. InstrList: array of taicpu;
  9594. InstrMax, Index: Integer;
  9595. const
  9596. {$ifdef DEBUG_AOPTCPU}
  9597. SNoFlags: shortstring = ' so the flags aren''t modified';
  9598. {$else DEBUG_AOPTCPU}
  9599. SNoFlags = '';
  9600. {$endif DEBUG_AOPTCPU}
  9601. begin
  9602. Result:=false;
  9603. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  9604. begin
  9605. if MatchInstruction(hp1, A_TEST, [S_B]) and
  9606. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  9607. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9608. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  9609. GetNextInstruction(hp1, hp2) and
  9610. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  9611. { Change from: To:
  9612. set(C) %reg j(~C) label
  9613. test %reg,%reg/cmp $0,%reg
  9614. je label
  9615. set(C) %reg j(C) label
  9616. test %reg,%reg/cmp $0,%reg
  9617. jne label
  9618. (Also do something similar with sete/setne instead of je/jne)
  9619. }
  9620. begin
  9621. { Before we do anything else, we need to check the instructions
  9622. in between SETcc and TEST to make sure they don't modify the
  9623. FLAGS register - if -O2 or under, there won't be any
  9624. instructions between SET and TEST }
  9625. TransferUsedRegs(TmpUsedRegs);
  9626. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  9627. if (cs_opt_level3 in current_settings.optimizerswitches) then
  9628. begin
  9629. next := p;
  9630. SetLength(InstrList, 0);
  9631. InstrMax := -1;
  9632. PotentialModified := False;
  9633. { Make a note of every instruction that modifies the FLAGS
  9634. register }
  9635. while GetNextInstruction(next, next) and (next <> hp1) do
  9636. begin
  9637. if next.typ <> ait_instruction then
  9638. { GetNextInstructionUsingReg should have returned False }
  9639. InternalError(2021051701);
  9640. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  9641. begin
  9642. case taicpu(next).opcode of
  9643. A_SETcc,
  9644. A_CMOVcc,
  9645. A_Jcc:
  9646. begin
  9647. if PotentialModified then
  9648. { Not safe because the flags were modified earlier }
  9649. Exit
  9650. else
  9651. { Condition is the same as the initial SETcc, so this is safe
  9652. (don't add to instruction list though) }
  9653. Continue;
  9654. end;
  9655. A_ADD:
  9656. begin
  9657. if (taicpu(next).opsize = S_B) or
  9658. { LEA doesn't support 8-bit operands }
  9659. (taicpu(next).oper[1]^.typ <> top_reg) or
  9660. { Must write to a register }
  9661. (taicpu(next).oper[0]^.typ = top_ref) then
  9662. { Require a constant or a register }
  9663. Exit;
  9664. PotentialModified := True;
  9665. end;
  9666. A_SUB:
  9667. begin
  9668. if (taicpu(next).opsize = S_B) or
  9669. { LEA doesn't support 8-bit operands }
  9670. (taicpu(next).oper[1]^.typ <> top_reg) or
  9671. { Must write to a register }
  9672. (taicpu(next).oper[0]^.typ <> top_const) or
  9673. (taicpu(next).oper[0]^.val = $80000000) then
  9674. { Can't subtract a register with LEA - also
  9675. check that the value isn't -2^31, as this
  9676. can't be negated }
  9677. Exit;
  9678. PotentialModified := True;
  9679. end;
  9680. A_SAL,
  9681. A_SHL:
  9682. begin
  9683. if (taicpu(next).opsize = S_B) or
  9684. { LEA doesn't support 8-bit operands }
  9685. (taicpu(next).oper[1]^.typ <> top_reg) or
  9686. { Must write to a register }
  9687. (taicpu(next).oper[0]^.typ <> top_const) or
  9688. (taicpu(next).oper[0]^.val < 0) or
  9689. (taicpu(next).oper[0]^.val > 3) then
  9690. Exit;
  9691. PotentialModified := True;
  9692. end;
  9693. A_IMUL:
  9694. begin
  9695. if (taicpu(next).ops <> 3) or
  9696. (taicpu(next).oper[1]^.typ <> top_reg) or
  9697. { Must write to a register }
  9698. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  9699. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  9700. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  9701. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  9702. Exit
  9703. else
  9704. PotentialModified := True;
  9705. end;
  9706. else
  9707. { Don't know how to change this, so abort }
  9708. Exit;
  9709. end;
  9710. { Contains highest index (so instruction count - 1) }
  9711. Inc(InstrMax);
  9712. if InstrMax > High(InstrList) then
  9713. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  9714. InstrList[InstrMax] := taicpu(next);
  9715. end;
  9716. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  9717. end;
  9718. if not Assigned(next) or (next <> hp1) then
  9719. { It should be equal to hp1 }
  9720. InternalError(2021051702);
  9721. { Cycle through each instruction and check to see if we can
  9722. change them to versions that don't modify the flags }
  9723. if (InstrMax >= 0) then
  9724. begin
  9725. for Index := 0 to InstrMax do
  9726. case InstrList[Index].opcode of
  9727. A_ADD:
  9728. begin
  9729. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  9730. InstrList[Index].opcode := A_LEA;
  9731. reference_reset(NewRef, 1, []);
  9732. NewRef.base := InstrList[Index].oper[1]^.reg;
  9733. if InstrList[Index].oper[0]^.typ = top_reg then
  9734. begin
  9735. NewRef.index := InstrList[Index].oper[0]^.reg;
  9736. NewRef.scalefactor := 1;
  9737. end
  9738. else
  9739. NewRef.offset := InstrList[Index].oper[0]^.val;
  9740. InstrList[Index].loadref(0, NewRef);
  9741. end;
  9742. A_SUB:
  9743. begin
  9744. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  9745. InstrList[Index].opcode := A_LEA;
  9746. reference_reset(NewRef, 1, []);
  9747. NewRef.base := InstrList[Index].oper[1]^.reg;
  9748. NewRef.offset := -InstrList[Index].oper[0]^.val;
  9749. InstrList[Index].loadref(0, NewRef);
  9750. end;
  9751. A_SHL,
  9752. A_SAL:
  9753. begin
  9754. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  9755. InstrList[Index].opcode := A_LEA;
  9756. reference_reset(NewRef, 1, []);
  9757. NewRef.index := InstrList[Index].oper[1]^.reg;
  9758. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  9759. InstrList[Index].loadref(0, NewRef);
  9760. end;
  9761. A_IMUL:
  9762. begin
  9763. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  9764. InstrList[Index].opcode := A_LEA;
  9765. reference_reset(NewRef, 1, []);
  9766. NewRef.index := InstrList[Index].oper[1]^.reg;
  9767. case InstrList[Index].oper[0]^.val of
  9768. 2, 4, 8:
  9769. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  9770. else {3, 5 and 9}
  9771. begin
  9772. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  9773. NewRef.base := InstrList[Index].oper[1]^.reg;
  9774. end;
  9775. end;
  9776. InstrList[Index].loadref(0, NewRef);
  9777. end;
  9778. else
  9779. InternalError(2021051710);
  9780. end;
  9781. end;
  9782. { Mark the FLAGS register as used across this whole block }
  9783. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  9784. end;
  9785. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  9786. JumpC := taicpu(hp2).condition;
  9787. Unconditional := False;
  9788. if conditions_equal(JumpC, C_E) then
  9789. SetC := inverse_cond(taicpu(p).condition)
  9790. else if conditions_equal(JumpC, C_NE) then
  9791. SetC := taicpu(p).condition
  9792. else
  9793. { We've got something weird here (and inefficent) }
  9794. begin
  9795. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  9796. SetC := C_NONE;
  9797. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  9798. if condition_in(C_AE, JumpC) then
  9799. Unconditional := True
  9800. else
  9801. { Not sure what to do with this jump - drop out }
  9802. Exit;
  9803. end;
  9804. RemoveInstruction(hp1);
  9805. if Unconditional then
  9806. MakeUnconditional(taicpu(hp2))
  9807. else
  9808. begin
  9809. if SetC = C_NONE then
  9810. InternalError(2018061402);
  9811. taicpu(hp2).SetCondition(SetC);
  9812. end;
  9813. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  9814. TmpUsedRegs }
  9815. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  9816. begin
  9817. RemoveCurrentp(p, hp2);
  9818. if taicpu(hp2).opcode = A_SETcc then
  9819. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  9820. else
  9821. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  9822. end
  9823. else
  9824. if taicpu(hp2).opcode = A_SETcc then
  9825. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  9826. else
  9827. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  9828. Result := True;
  9829. end
  9830. else if
  9831. { Make sure the instructions are adjacent }
  9832. (
  9833. not (cs_opt_level3 in current_settings.optimizerswitches) or
  9834. GetNextInstruction(p, hp1)
  9835. ) and
  9836. MatchInstruction(hp1, A_MOV, [S_B]) and
  9837. { Writing to memory is allowed }
  9838. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  9839. begin
  9840. {
  9841. Watch out for sequences such as:
  9842. set(c)b %regb
  9843. movb %regb,(ref)
  9844. movb $0,1(ref)
  9845. movb $0,2(ref)
  9846. movb $0,3(ref)
  9847. Much more efficient to turn it into:
  9848. movl $0,%regl
  9849. set(c)b %regb
  9850. movl %regl,(ref)
  9851. Or:
  9852. set(c)b %regb
  9853. movzbl %regb,%regl
  9854. movl %regl,(ref)
  9855. }
  9856. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  9857. GetNextInstruction(hp1, hp2) and
  9858. MatchInstruction(hp2, A_MOV, [S_B]) and
  9859. (taicpu(hp2).oper[1]^.typ = top_ref) and
  9860. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  9861. begin
  9862. { Don't do anything else except set Result to True }
  9863. end
  9864. else
  9865. begin
  9866. if taicpu(p).oper[0]^.typ = top_reg then
  9867. begin
  9868. TransferUsedRegs(TmpUsedRegs);
  9869. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  9870. end;
  9871. { If it's not a register, it's a memory address }
  9872. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  9873. begin
  9874. { Even if the register is still in use, we can minimise the
  9875. pipeline stall by changing the MOV into another SETcc. }
  9876. taicpu(hp1).opcode := A_SETcc;
  9877. taicpu(hp1).condition := taicpu(p).condition;
  9878. if taicpu(hp1).oper[1]^.typ = top_ref then
  9879. begin
  9880. { Swapping the operand pointers like this is probably a
  9881. bit naughty, but it is far faster than using loadoper
  9882. to transfer the reference from oper[1] to oper[0] if
  9883. you take into account the extra procedure calls and
  9884. the memory allocation and deallocation required }
  9885. OperPtr := taicpu(hp1).oper[1];
  9886. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  9887. taicpu(hp1).oper[0] := OperPtr;
  9888. end
  9889. else
  9890. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  9891. taicpu(hp1).clearop(1);
  9892. taicpu(hp1).ops := 1;
  9893. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  9894. end
  9895. else
  9896. begin
  9897. if taicpu(hp1).oper[1]^.typ = top_reg then
  9898. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  9899. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  9900. RemoveInstruction(hp1);
  9901. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  9902. end
  9903. end;
  9904. Result := True;
  9905. end;
  9906. end;
  9907. end;
  9908. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  9909. var
  9910. hp1: tai;
  9911. Count: Integer;
  9912. OrigLabel: TAsmLabel;
  9913. begin
  9914. result := False;
  9915. { Sometimes, the optimisations below can permit this }
  9916. RemoveDeadCodeAfterJump(p);
  9917. 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
  9918. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  9919. begin
  9920. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  9921. { Also a side-effect of optimisations }
  9922. if CollapseZeroDistJump(p, OrigLabel) then
  9923. begin
  9924. Result := True;
  9925. Exit;
  9926. end;
  9927. hp1 := GetLabelWithSym(OrigLabel);
  9928. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  9929. begin
  9930. if taicpu(hp1).opcode = A_RET then
  9931. begin
  9932. {
  9933. change
  9934. jmp .L1
  9935. ...
  9936. .L1:
  9937. ret
  9938. into
  9939. ret
  9940. }
  9941. begin
  9942. ConvertJumpToRET(p, hp1);
  9943. result:=true;
  9944. end;
  9945. end
  9946. else if (cs_opt_level3 in current_settings.optimizerswitches) and
  9947. not (cs_opt_size in current_settings.optimizerswitches) and
  9948. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  9949. begin
  9950. Result := True;
  9951. Exit;
  9952. end;
  9953. end;
  9954. end;
  9955. end;
  9956. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  9957. begin
  9958. CanBeCMOV:=assigned(p) and
  9959. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  9960. { we can't use cmov ref,reg because
  9961. ref could be nil and cmov still throws an exception
  9962. if ref=nil but the mov isn't done (FK)
  9963. or ((taicpu(p).oper[0]^.typ = top_ref) and
  9964. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  9965. }
  9966. (taicpu(p).oper[1]^.typ = top_reg) and
  9967. (
  9968. (taicpu(p).oper[0]^.typ = top_reg) or
  9969. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  9970. it is not expected that this can cause a seg. violation }
  9971. (
  9972. (taicpu(p).oper[0]^.typ = top_ref) and
  9973. IsRefSafe(taicpu(p).oper[0]^.ref)
  9974. )
  9975. );
  9976. end;
  9977. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  9978. var
  9979. hp1,hp2: tai;
  9980. {$ifndef i8086}
  9981. hp3,hp4,hpmov2, hp5: tai;
  9982. l : Longint;
  9983. condition : TAsmCond;
  9984. {$endif i8086}
  9985. carryadd_opcode : TAsmOp;
  9986. symbol: TAsmSymbol;
  9987. increg, tmpreg: TRegister;
  9988. begin
  9989. result:=false;
  9990. if GetNextInstruction(p,hp1) then
  9991. begin
  9992. if (hp1.typ=ait_label) then
  9993. begin
  9994. Result := DoSETccLblRETOpt(p, tai_label(hp1));
  9995. Exit;
  9996. end
  9997. else if (hp1.typ<>ait_instruction) then
  9998. Exit;
  9999. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  10000. if (
  10001. (
  10002. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  10003. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  10004. (Taicpu(hp1).oper[0]^.val=1)
  10005. ) or
  10006. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  10007. ) and
  10008. GetNextInstruction(hp1,hp2) and
  10009. SkipAligns(hp2, hp2) and
  10010. (hp2.typ = ait_label) and
  10011. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  10012. { jb @@1 cmc
  10013. inc/dec operand --> adc/sbb operand,0
  10014. @@1:
  10015. ... and ...
  10016. jnb @@1
  10017. inc/dec operand --> adc/sbb operand,0
  10018. @@1: }
  10019. begin
  10020. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  10021. begin
  10022. case taicpu(hp1).opcode of
  10023. A_INC,
  10024. A_ADD:
  10025. carryadd_opcode:=A_ADC;
  10026. A_DEC,
  10027. A_SUB:
  10028. carryadd_opcode:=A_SBB;
  10029. else
  10030. InternalError(2021011001);
  10031. end;
  10032. Taicpu(p).clearop(0);
  10033. Taicpu(p).ops:=0;
  10034. Taicpu(p).is_jmp:=false;
  10035. Taicpu(p).opcode:=A_CMC;
  10036. Taicpu(p).condition:=C_NONE;
  10037. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  10038. Taicpu(hp1).ops:=2;
  10039. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10040. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10041. else
  10042. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10043. Taicpu(hp1).loadconst(0,0);
  10044. Taicpu(hp1).opcode:=carryadd_opcode;
  10045. result:=true;
  10046. exit;
  10047. end
  10048. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  10049. begin
  10050. case taicpu(hp1).opcode of
  10051. A_INC,
  10052. A_ADD:
  10053. carryadd_opcode:=A_ADC;
  10054. A_DEC,
  10055. A_SUB:
  10056. carryadd_opcode:=A_SBB;
  10057. else
  10058. InternalError(2021011002);
  10059. end;
  10060. Taicpu(hp1).ops:=2;
  10061. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  10062. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  10063. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  10064. else
  10065. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  10066. Taicpu(hp1).loadconst(0,0);
  10067. Taicpu(hp1).opcode:=carryadd_opcode;
  10068. RemoveCurrentP(p, hp1);
  10069. result:=true;
  10070. exit;
  10071. end
  10072. {
  10073. jcc @@1 setcc tmpreg
  10074. inc/dec/add/sub operand -> (movzx tmpreg)
  10075. @@1: add/sub tmpreg,operand
  10076. While this increases code size slightly, it makes the code much faster if the
  10077. jump is unpredictable
  10078. }
  10079. else if not(cs_opt_size in current_settings.optimizerswitches) then
  10080. begin
  10081. { search for an available register which is volatile }
  10082. increg := GetIntRegisterBetween(R_SUBL, UsedRegs, p, hp1);
  10083. if increg <> NR_NO then
  10084. begin
  10085. { We don't need to check if tmpreg is in hp1 or not, because
  10086. it will be marked as in use at p (if not, this is
  10087. indictive of a compiler bug). }
  10088. TAsmLabel(symbol).decrefs;
  10089. Taicpu(p).clearop(0);
  10090. Taicpu(p).ops:=1;
  10091. Taicpu(p).is_jmp:=false;
  10092. Taicpu(p).opcode:=A_SETcc;
  10093. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  10094. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  10095. Taicpu(p).loadreg(0,increg);
  10096. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  10097. begin
  10098. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  10099. R_SUBW:
  10100. begin
  10101. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBW);
  10102. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  10103. end;
  10104. R_SUBD:
  10105. begin
  10106. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10107. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10108. end;
  10109. {$ifdef x86_64}
  10110. R_SUBQ:
  10111. begin
  10112. { MOVZX doesn't have a 64-bit variant, because
  10113. the 32-bit version implicitly zeroes the
  10114. upper 32-bits of the destination register }
  10115. tmpreg := newreg(R_INTREGISTER,getsupreg(increg),R_SUBD);
  10116. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  10117. setsubreg(tmpreg, R_SUBQ);
  10118. end;
  10119. {$endif x86_64}
  10120. else
  10121. Internalerror(2020030601);
  10122. end;
  10123. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  10124. asml.InsertAfter(hp2,p);
  10125. end
  10126. else
  10127. tmpreg := increg;
  10128. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  10129. begin
  10130. Taicpu(hp1).ops:=2;
  10131. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  10132. end;
  10133. Taicpu(hp1).loadreg(0,tmpreg);
  10134. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  10135. Result := True;
  10136. { p is no longer a Jcc instruction, so exit }
  10137. Exit;
  10138. end;
  10139. end;
  10140. end;
  10141. { Detect the following:
  10142. jmp<cond> @Lbl1
  10143. jmp @Lbl2
  10144. ...
  10145. @Lbl1:
  10146. ret
  10147. Change to:
  10148. jmp<inv_cond> @Lbl2
  10149. ret
  10150. }
  10151. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  10152. begin
  10153. hp2:=getlabelwithsym(TAsmLabel(symbol));
  10154. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  10155. MatchInstruction(hp2,A_RET,[S_NO]) then
  10156. begin
  10157. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  10158. { Change label address to that of the unconditional jump }
  10159. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  10160. TAsmLabel(symbol).DecRefs;
  10161. taicpu(hp1).opcode := A_RET;
  10162. taicpu(hp1).is_jmp := false;
  10163. taicpu(hp1).ops := taicpu(hp2).ops;
  10164. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  10165. case taicpu(hp2).ops of
  10166. 0:
  10167. taicpu(hp1).clearop(0);
  10168. 1:
  10169. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  10170. else
  10171. internalerror(2016041302);
  10172. end;
  10173. end;
  10174. {$ifndef i8086}
  10175. end
  10176. {
  10177. convert
  10178. j<c> .L1
  10179. mov 1,reg
  10180. jmp .L2
  10181. .L1
  10182. mov 0,reg
  10183. .L2
  10184. into
  10185. mov 0,reg
  10186. set<not(c)> reg
  10187. take care of alignment and that the mov 0,reg is not converted into a xor as this
  10188. would destroy the flag contents
  10189. }
  10190. else if MatchInstruction(hp1,A_MOV,[]) and
  10191. MatchOpType(taicpu(hp1),top_const,top_reg) and
  10192. {$ifdef i386}
  10193. (
  10194. { Under i386, ESI, EDI, EBP and ESP
  10195. don't have an 8-bit representation }
  10196. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  10197. ) and
  10198. {$endif i386}
  10199. (taicpu(hp1).oper[0]^.val=1) and
  10200. GetNextInstruction(hp1,hp2) and
  10201. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  10202. GetNextInstruction(hp2,hp3) and
  10203. { skip align }
  10204. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  10205. (hp3.typ=ait_label) and
  10206. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  10207. (tai_label(hp3).labsym.getrefs=1) and
  10208. GetNextInstruction(hp3,hp4) and
  10209. MatchInstruction(hp4,A_MOV,[]) and
  10210. MatchOpType(taicpu(hp4),top_const,top_reg) and
  10211. (taicpu(hp4).oper[0]^.val=0) and
  10212. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  10213. GetNextInstruction(hp4,hp5) and
  10214. (hp5.typ=ait_label) and
  10215. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  10216. (tai_label(hp5).labsym.getrefs=1) then
  10217. begin
  10218. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  10219. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  10220. { remove last label }
  10221. RemoveInstruction(hp5);
  10222. { remove second label }
  10223. RemoveInstruction(hp3);
  10224. { if align is present remove it }
  10225. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  10226. RemoveInstruction(hp3);
  10227. { remove jmp }
  10228. RemoveInstruction(hp2);
  10229. if taicpu(hp1).opsize=S_B then
  10230. RemoveInstruction(hp1)
  10231. else
  10232. taicpu(hp1).loadconst(0,0);
  10233. taicpu(hp4).opcode:=A_SETcc;
  10234. taicpu(hp4).opsize:=S_B;
  10235. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  10236. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  10237. taicpu(hp4).opercnt:=1;
  10238. taicpu(hp4).ops:=1;
  10239. taicpu(hp4).freeop(1);
  10240. RemoveCurrentP(p);
  10241. Result:=true;
  10242. exit;
  10243. end
  10244. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  10245. begin
  10246. { check for
  10247. jCC xxx
  10248. <several movs>
  10249. xxx:
  10250. Also spot:
  10251. Jcc xxx
  10252. <several movs>
  10253. jmp xxx
  10254. Change to:
  10255. <several cmovs with inverted condition>
  10256. jmp xxx
  10257. }
  10258. l:=0;
  10259. while assigned(hp1) and
  10260. CanBeCMOV(hp1) and
  10261. { stop on labels }
  10262. not(hp1.typ=ait_label) do
  10263. begin
  10264. inc(l);
  10265. hp5 := hp1;
  10266. GetNextInstruction(hp1,hp1);
  10267. end;
  10268. if assigned(hp1) then
  10269. begin
  10270. TransferUsedRegs(TmpUsedRegs);
  10271. if (
  10272. MatchInstruction(hp1, A_JMP, []) and
  10273. (JumpTargetOp(taicpu(hp1))^.typ=top_ref) and
  10274. (JumpTargetOp(taicpu(hp1))^.ref^.symbol=symbol)
  10275. ) or
  10276. FindLabel(tasmlabel(symbol),hp1) then
  10277. begin
  10278. if (l<=4) and (l>0) then
  10279. begin
  10280. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  10281. condition:=inverse_cond(taicpu(p).condition);
  10282. UpdateUsedRegs(tai(p.next));
  10283. GetNextInstruction(p,hp1);
  10284. repeat
  10285. if not Assigned(hp1) then
  10286. InternalError(2018062900);
  10287. taicpu(hp1).opcode:=A_CMOVcc;
  10288. taicpu(hp1).condition:=condition;
  10289. UpdateUsedRegs(tai(hp1.next));
  10290. GetNextInstruction(hp1,hp1);
  10291. until not(CanBeCMOV(hp1));
  10292. { Remember what hp1 is in case there's multiple aligns to get rid of }
  10293. hp2 := hp1;
  10294. repeat
  10295. if not Assigned(hp2) then
  10296. InternalError(2018062910);
  10297. case hp2.typ of
  10298. ait_label:
  10299. { What we expected - break out of the loop (it won't be a dead label at the top of
  10300. a cluster because that was optimised at an earlier stage) }
  10301. Break;
  10302. ait_align:
  10303. { Go to the next entry until a label is found (may be multiple aligns before it) }
  10304. begin
  10305. hp2 := tai(hp2.Next);
  10306. Continue;
  10307. end;
  10308. ait_instruction:
  10309. begin
  10310. if taicpu(hp2).opcode<>A_JMP then
  10311. InternalError(2018062912);
  10312. { This is the Jcc @Lbl; <several movs>; JMP @Lbl variant }
  10313. Break;
  10314. end
  10315. else
  10316. begin
  10317. { Might be a comment or temporary allocation entry }
  10318. if not (hp2.typ in SkipInstr) then
  10319. InternalError(2018062911);
  10320. hp2 := tai(hp2.Next);
  10321. Continue;
  10322. end;
  10323. end;
  10324. until False;
  10325. { Now we can safely decrement the reference count }
  10326. tasmlabel(symbol).decrefs;
  10327. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  10328. { Remove the original jump }
  10329. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  10330. if hp2.typ=ait_instruction then
  10331. begin
  10332. p:=hp2;
  10333. Result:=True;
  10334. end
  10335. else
  10336. begin
  10337. UpdateUsedRegs(tai(hp2.next));
  10338. Result:=GetNextInstruction(hp2, p); { Instruction after the label }
  10339. { Remove the label if this is its final reference }
  10340. if (tasmlabel(symbol).getrefs=0) then
  10341. StripLabelFast(hp1);
  10342. end;
  10343. exit;
  10344. end;
  10345. end
  10346. else
  10347. begin
  10348. { check further for
  10349. jCC xxx
  10350. <several movs 1>
  10351. jmp yyy
  10352. xxx:
  10353. <several movs 2>
  10354. yyy:
  10355. }
  10356. { hp2 points to jmp yyy }
  10357. hp2:=hp1;
  10358. { skip hp1 to xxx (or an align right before it) }
  10359. GetNextInstruction(hp1, hp1);
  10360. if assigned(hp2) and
  10361. assigned(hp1) and
  10362. (l<=3) and
  10363. (hp2.typ=ait_instruction) and
  10364. (taicpu(hp2).is_jmp) and
  10365. (taicpu(hp2).condition=C_None) and
  10366. { real label and jump, no further references to the
  10367. label are allowed }
  10368. (tasmlabel(symbol).getrefs=1) and
  10369. FindLabel(tasmlabel(symbol),hp1) then
  10370. begin
  10371. l:=0;
  10372. { skip hp1 to <several moves 2> }
  10373. if (hp1.typ = ait_align) then
  10374. GetNextInstruction(hp1, hp1);
  10375. GetNextInstruction(hp1, hpmov2);
  10376. hp1 := hpmov2;
  10377. while assigned(hp1) and
  10378. CanBeCMOV(hp1) do
  10379. begin
  10380. inc(l);
  10381. hp5 := hp1;
  10382. GetNextInstruction(hp1, hp1);
  10383. end;
  10384. { hp1 points to yyy (or an align right before it) }
  10385. hp3 := hp1;
  10386. if assigned(hp1) and
  10387. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  10388. begin
  10389. AllocRegBetween(NR_DEFAULTFLAGS, p, hp5, TmpUsedRegs);
  10390. condition:=inverse_cond(taicpu(p).condition);
  10391. UpdateUsedRegs(tai(p.next));
  10392. GetNextInstruction(p,hp1);
  10393. repeat
  10394. taicpu(hp1).opcode:=A_CMOVcc;
  10395. taicpu(hp1).condition:=condition;
  10396. UpdateUsedRegs(tai(hp1.next));
  10397. GetNextInstruction(hp1,hp1);
  10398. until not(assigned(hp1)) or
  10399. not(CanBeCMOV(hp1));
  10400. condition:=inverse_cond(condition);
  10401. if GetLastInstruction(hpmov2,hp1) then
  10402. UpdateUsedRegs(tai(hp1.next));
  10403. hp1 := hpmov2;
  10404. { hp1 is now at <several movs 2> }
  10405. while Assigned(hp1) and CanBeCMOV(hp1) do
  10406. begin
  10407. taicpu(hp1).opcode:=A_CMOVcc;
  10408. taicpu(hp1).condition:=condition;
  10409. UpdateUsedRegs(tai(hp1.next));
  10410. GetNextInstruction(hp1,hp1);
  10411. end;
  10412. hp1 := p;
  10413. { Get first instruction after label }
  10414. UpdateUsedRegs(tai(hp3.next));
  10415. GetNextInstruction(hp3, p);
  10416. if assigned(p) and (hp3.typ = ait_align) then
  10417. GetNextInstruction(p, p);
  10418. { Don't dereference yet, as doing so will cause
  10419. GetNextInstruction to skip the label and
  10420. optional align marker. [Kit] }
  10421. GetNextInstruction(hp2, hp4);
  10422. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  10423. { remove jCC }
  10424. RemoveInstruction(hp1);
  10425. { Now we can safely decrement it }
  10426. tasmlabel(symbol).decrefs;
  10427. { Remove label xxx (it will have a ref of zero due to the initial check }
  10428. StripLabelFast(hp4);
  10429. { remove jmp }
  10430. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  10431. RemoveInstruction(hp2);
  10432. { As before, now we can safely decrement it }
  10433. tasmlabel(symbol).decrefs;
  10434. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  10435. if tasmlabel(symbol).getrefs = 0 then
  10436. StripLabelFast(hp3);
  10437. if Assigned(p) then
  10438. result:=true;
  10439. exit;
  10440. end;
  10441. end;
  10442. end;
  10443. end;
  10444. {$endif i8086}
  10445. end;
  10446. end;
  10447. end;
  10448. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  10449. var
  10450. hp1,hp2,hp3: tai;
  10451. reg_and_hp1_is_instr, RegUsed, AndTest: Boolean;
  10452. NewSize: TOpSize;
  10453. NewRegSize: TSubRegister;
  10454. Limit: TCgInt;
  10455. SwapOper: POper;
  10456. begin
  10457. result:=false;
  10458. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  10459. GetNextInstruction(p,hp1) and
  10460. (hp1.typ = ait_instruction);
  10461. if reg_and_hp1_is_instr and
  10462. (
  10463. (taicpu(hp1).opcode <> A_LEA) or
  10464. { If the LEA instruction can be converted into an arithmetic instruction,
  10465. it may be possible to then fold it. }
  10466. (
  10467. { If the flags register is in use, don't change the instruction
  10468. to an ADD otherwise this will scramble the flags. [Kit] }
  10469. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  10470. ConvertLEA(taicpu(hp1))
  10471. )
  10472. ) and
  10473. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  10474. GetNextInstruction(hp1,hp2) and
  10475. MatchInstruction(hp2,A_MOV,[]) and
  10476. (taicpu(hp2).oper[0]^.typ = top_reg) and
  10477. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  10478. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  10479. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  10480. {$ifdef i386}
  10481. { not all registers have byte size sub registers on i386 }
  10482. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  10483. {$endif i386}
  10484. (((taicpu(hp1).ops=2) and
  10485. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  10486. ((taicpu(hp1).ops=1) and
  10487. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  10488. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  10489. begin
  10490. { change movsX/movzX reg/ref, reg2
  10491. add/sub/or/... reg3/$const, reg2
  10492. mov reg2 reg/ref
  10493. to add/sub/or/... reg3/$const, reg/ref }
  10494. { by example:
  10495. movswl %si,%eax movswl %si,%eax p
  10496. decl %eax addl %edx,%eax hp1
  10497. movw %ax,%si movw %ax,%si hp2
  10498. ->
  10499. movswl %si,%eax movswl %si,%eax p
  10500. decw %eax addw %edx,%eax hp1
  10501. movw %ax,%si movw %ax,%si hp2
  10502. }
  10503. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  10504. {
  10505. ->
  10506. movswl %si,%eax movswl %si,%eax p
  10507. decw %si addw %dx,%si hp1
  10508. movw %ax,%si movw %ax,%si hp2
  10509. }
  10510. case taicpu(hp1).ops of
  10511. 1:
  10512. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  10513. 2:
  10514. begin
  10515. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  10516. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  10517. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  10518. end;
  10519. else
  10520. internalerror(2008042702);
  10521. end;
  10522. {
  10523. ->
  10524. decw %si addw %dx,%si p
  10525. }
  10526. DebugMsg(SPeepholeOptimization + 'var3',p);
  10527. RemoveCurrentP(p, hp1);
  10528. RemoveInstruction(hp2);
  10529. Result := True;
  10530. Exit;
  10531. end;
  10532. if reg_and_hp1_is_instr and
  10533. (taicpu(hp1).opcode = A_MOV) and
  10534. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  10535. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  10536. {$ifdef x86_64}
  10537. { check for implicit extension to 64 bit }
  10538. or
  10539. ((taicpu(p).opsize in [S_BL,S_WL]) and
  10540. (taicpu(hp1).opsize=S_Q) and
  10541. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  10542. )
  10543. {$endif x86_64}
  10544. )
  10545. then
  10546. begin
  10547. { change
  10548. movx %reg1,%reg2
  10549. mov %reg2,%reg3
  10550. dealloc %reg2
  10551. into
  10552. movx %reg,%reg3
  10553. }
  10554. TransferUsedRegs(TmpUsedRegs);
  10555. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10556. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  10557. begin
  10558. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  10559. {$ifdef x86_64}
  10560. if (taicpu(p).opsize in [S_BL,S_WL]) and
  10561. (taicpu(hp1).opsize=S_Q) then
  10562. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  10563. else
  10564. {$endif x86_64}
  10565. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  10566. RemoveInstruction(hp1);
  10567. Result := True;
  10568. Exit;
  10569. end;
  10570. end;
  10571. if reg_and_hp1_is_instr and
  10572. ((taicpu(hp1).opcode=A_MOV) or
  10573. (taicpu(hp1).opcode=A_ADD) or
  10574. (taicpu(hp1).opcode=A_SUB) or
  10575. (taicpu(hp1).opcode=A_CMP) or
  10576. (taicpu(hp1).opcode=A_OR) or
  10577. (taicpu(hp1).opcode=A_XOR) or
  10578. (taicpu(hp1).opcode=A_AND)
  10579. ) and
  10580. (taicpu(hp1).oper[1]^.typ = top_reg) then
  10581. begin
  10582. AndTest := (taicpu(hp1).opcode=A_AND) and
  10583. GetNextInstruction(hp1, hp2) and
  10584. (hp2.typ = ait_instruction) and
  10585. (
  10586. (
  10587. (taicpu(hp2).opcode=A_TEST) and
  10588. (
  10589. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[1]^.reg) or
  10590. MatchOperand(taicpu(hp2).oper[0]^, -1) or
  10591. (
  10592. { If the AND and TEST instructions share a constant, this is also valid }
  10593. (taicpu(hp1).oper[0]^.typ = top_const) and
  10594. MatchOperand(taicpu(hp2).oper[0]^, taicpu(hp1).oper[0]^.val)
  10595. )
  10596. ) and
  10597. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10598. ) or
  10599. (
  10600. (taicpu(hp2).opcode=A_CMP) and
  10601. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  10602. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[1]^.reg)
  10603. )
  10604. );
  10605. { change
  10606. movx (oper),%reg2
  10607. and $x,%reg2
  10608. test %reg2,%reg2
  10609. dealloc %reg2
  10610. into
  10611. op %reg1,%reg3
  10612. if the second op accesses only the bits stored in reg1
  10613. }
  10614. if ((taicpu(p).oper[0]^.typ=top_reg) or
  10615. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  10616. (taicpu(hp1).oper[0]^.typ = top_const) and
  10617. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  10618. AndTest then
  10619. begin
  10620. { Check if the AND constant is in range }
  10621. case taicpu(p).opsize of
  10622. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10623. begin
  10624. NewSize := S_B;
  10625. Limit := $FF;
  10626. end;
  10627. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10628. begin
  10629. NewSize := S_W;
  10630. Limit := $FFFF;
  10631. end;
  10632. {$ifdef x86_64}
  10633. S_LQ:
  10634. begin
  10635. NewSize := S_L;
  10636. Limit := $FFFFFFFF;
  10637. end;
  10638. {$endif x86_64}
  10639. else
  10640. InternalError(2021120303);
  10641. end;
  10642. if (
  10643. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val) or
  10644. { Check for negative operands }
  10645. (((not taicpu(hp1).oper[0]^.val) and Limit) = (not taicpu(hp1).oper[0]^.val))
  10646. ) and
  10647. GetNextInstruction(hp2,hp3) and
  10648. MatchInstruction(hp3,A_Jcc,A_Setcc,A_CMOVcc,[]) and
  10649. (taicpu(hp3).condition in [C_E,C_NE]) then
  10650. begin
  10651. TransferUsedRegs(TmpUsedRegs);
  10652. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  10653. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  10654. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  10655. begin
  10656. DebugMsg(SPeepholeOptimization + 'MovxAndTest2Test done',p);
  10657. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10658. taicpu(hp1).opcode := A_TEST;
  10659. taicpu(hp1).opsize := NewSize;
  10660. RemoveInstruction(hp2);
  10661. RemoveCurrentP(p, hp1);
  10662. Result:=true;
  10663. exit;
  10664. end;
  10665. end;
  10666. end;
  10667. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  10668. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  10669. (taicpu(hp1).opsize=S_B)) or
  10670. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  10671. (taicpu(hp1).opsize=S_W))
  10672. {$ifdef x86_64}
  10673. or ((taicpu(p).opsize=S_LQ) and
  10674. (taicpu(hp1).opsize=S_L))
  10675. {$endif x86_64}
  10676. ) and
  10677. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  10678. begin
  10679. { change
  10680. movx %reg1,%reg2
  10681. op %reg2,%reg3
  10682. dealloc %reg2
  10683. into
  10684. op %reg1,%reg3
  10685. if the second op accesses only the bits stored in reg1
  10686. }
  10687. TransferUsedRegs(TmpUsedRegs);
  10688. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10689. if AndTest then
  10690. begin
  10691. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10692. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10693. end
  10694. else
  10695. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10696. if not RegUsed then
  10697. begin
  10698. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 1',p);
  10699. if taicpu(p).oper[0]^.typ=top_reg then
  10700. begin
  10701. case taicpu(hp1).opsize of
  10702. S_B:
  10703. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  10704. S_W:
  10705. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  10706. S_L:
  10707. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  10708. else
  10709. Internalerror(2020102301);
  10710. end;
  10711. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  10712. end
  10713. else
  10714. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  10715. RemoveCurrentP(p);
  10716. if AndTest then
  10717. RemoveInstruction(hp2);
  10718. result:=true;
  10719. exit;
  10720. end;
  10721. end
  10722. else if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  10723. (
  10724. { Bitwise operations only }
  10725. (taicpu(hp1).opcode=A_AND) or
  10726. (taicpu(hp1).opcode=A_TEST) or
  10727. (
  10728. (taicpu(hp1).oper[0]^.typ = top_const) and
  10729. (
  10730. (taicpu(hp1).opcode=A_OR) or
  10731. (taicpu(hp1).opcode=A_XOR)
  10732. )
  10733. )
  10734. ) and
  10735. (
  10736. (taicpu(hp1).oper[0]^.typ = top_const) or
  10737. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  10738. not RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^)
  10739. ) then
  10740. begin
  10741. { change
  10742. movx %reg2,%reg2
  10743. op const,%reg2
  10744. into
  10745. op const,%reg2 (smaller version)
  10746. movx %reg2,%reg2
  10747. also change
  10748. movx %reg1,%reg2
  10749. and/test (oper),%reg2
  10750. dealloc %reg2
  10751. into
  10752. and/test (oper),%reg1
  10753. }
  10754. case taicpu(p).opsize of
  10755. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  10756. begin
  10757. NewSize := S_B;
  10758. NewRegSize := R_SUBL;
  10759. Limit := $FF;
  10760. end;
  10761. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  10762. begin
  10763. NewSize := S_W;
  10764. NewRegSize := R_SUBW;
  10765. Limit := $FFFF;
  10766. end;
  10767. {$ifdef x86_64}
  10768. S_LQ:
  10769. begin
  10770. NewSize := S_L;
  10771. NewRegSize := R_SUBD;
  10772. Limit := $FFFFFFFF;
  10773. end;
  10774. {$endif x86_64}
  10775. else
  10776. Internalerror(2021120302);
  10777. end;
  10778. TransferUsedRegs(TmpUsedRegs);
  10779. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  10780. if AndTest then
  10781. begin
  10782. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  10783. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs);
  10784. end
  10785. else
  10786. RegUsed := RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs);
  10787. if
  10788. (
  10789. (taicpu(p).opcode = A_MOVZX) and
  10790. (
  10791. (taicpu(hp1).opcode=A_AND) or
  10792. (taicpu(hp1).opcode=A_TEST)
  10793. ) and
  10794. not (
  10795. { If both are references, then the final instruction will have
  10796. both operands as references, which is not allowed }
  10797. (taicpu(p).oper[0]^.typ = top_ref) and
  10798. (taicpu(hp1).oper[0]^.typ = top_ref)
  10799. ) and
  10800. not RegUsed
  10801. ) or
  10802. (
  10803. (
  10804. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) or
  10805. not RegUsed
  10806. ) and
  10807. (taicpu(p).oper[0]^.typ = top_reg) and
  10808. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10809. (taicpu(hp1).oper[0]^.typ = top_const) and
  10810. ((taicpu(hp1).oper[0]^.val and Limit) = taicpu(hp1).oper[0]^.val)
  10811. ) then
  10812. begin
  10813. {$if defined(i386) or defined(i8086)}
  10814. { If the target size is 8-bit, make sure we can actually encode it }
  10815. 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
  10816. Exit;
  10817. {$endif i386 or i8086}
  10818. DebugMsg(SPeepholeOptimization + 'MovxOp2Op 2',p);
  10819. taicpu(hp1).opsize := NewSize;
  10820. taicpu(hp1).loadoper(1, taicpu(p).oper[0]^);
  10821. if AndTest then
  10822. begin
  10823. RemoveInstruction(hp2);
  10824. if not RegUsed then
  10825. begin
  10826. taicpu(hp1).opcode := A_TEST;
  10827. if (taicpu(hp1).oper[0]^.typ = top_ref) then
  10828. begin
  10829. { Make sure the reference is the second operand }
  10830. SwapOper := taicpu(hp1).oper[0];
  10831. taicpu(hp1).oper[0] := taicpu(hp1).oper[1];
  10832. taicpu(hp1).oper[1] := SwapOper;
  10833. end;
  10834. end;
  10835. end;
  10836. case taicpu(hp1).oper[0]^.typ of
  10837. top_reg:
  10838. setsubreg(taicpu(hp1).oper[0]^.reg, NewRegSize);
  10839. top_const:
  10840. { For the AND/TEST case }
  10841. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and Limit;
  10842. else
  10843. ;
  10844. end;
  10845. if RegUsed then
  10846. begin
  10847. AsmL.Remove(p);
  10848. AsmL.InsertAfter(p, hp1);
  10849. p := hp1;
  10850. end
  10851. else
  10852. RemoveCurrentP(p, hp1);
  10853. result:=true;
  10854. exit;
  10855. end;
  10856. end;
  10857. end;
  10858. if reg_and_hp1_is_instr and
  10859. (taicpu(p).oper[0]^.typ = top_reg) and
  10860. (
  10861. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  10862. ) and
  10863. (taicpu(hp1).oper[0]^.typ = top_const) and
  10864. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10865. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10866. { Minimum shift value allowed is the bit difference between the sizes }
  10867. (taicpu(hp1).oper[0]^.val >=
  10868. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10869. 8 * (
  10870. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  10871. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10872. )
  10873. ) then
  10874. begin
  10875. { For:
  10876. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  10877. shl/sal ##, %reg1
  10878. Remove the movsx/movzx instruction if the shift overwrites the
  10879. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  10880. }
  10881. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  10882. RemoveCurrentP(p, hp1);
  10883. Result := True;
  10884. Exit;
  10885. end
  10886. else if reg_and_hp1_is_instr and
  10887. (taicpu(p).oper[0]^.typ = top_reg) and
  10888. (
  10889. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  10890. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  10891. ) and
  10892. (taicpu(hp1).oper[0]^.typ = top_const) and
  10893. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10894. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  10895. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  10896. (taicpu(hp1).oper[0]^.val <
  10897. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  10898. 8 * (
  10899. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  10900. )
  10901. ) then
  10902. begin
  10903. { For:
  10904. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  10905. sar ##, %reg1 shr ##, %reg1
  10906. Move the shift to before the movx instruction if the shift value
  10907. is not too large.
  10908. }
  10909. asml.Remove(hp1);
  10910. asml.InsertBefore(hp1, p);
  10911. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  10912. case taicpu(p).opsize of
  10913. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  10914. taicpu(hp1).opsize := S_B;
  10915. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  10916. taicpu(hp1).opsize := S_W;
  10917. {$ifdef x86_64}
  10918. S_LQ:
  10919. taicpu(hp1).opsize := S_L;
  10920. {$endif}
  10921. else
  10922. InternalError(2020112401);
  10923. end;
  10924. if (taicpu(hp1).opcode = A_SHR) then
  10925. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  10926. else
  10927. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  10928. Result := True;
  10929. end;
  10930. if reg_and_hp1_is_instr and
  10931. (taicpu(p).oper[0]^.typ = top_reg) and
  10932. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  10933. (
  10934. (taicpu(hp1).opcode = taicpu(p).opcode)
  10935. or ((taicpu(p).opcode = A_MOVZX) and ((taicpu(hp1).opcode = A_MOVSX){$ifdef x86_64} or (taicpu(hp1).opcode = A_MOVSXD){$endif x86_64}))
  10936. {$ifdef x86_64}
  10937. or ((taicpu(p).opcode = A_MOVSX) and (taicpu(hp1).opcode = A_MOVSXD))
  10938. {$endif x86_64}
  10939. ) then
  10940. begin
  10941. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  10942. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[0]^.reg) and
  10943. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  10944. begin
  10945. {
  10946. For example:
  10947. movzbw %al,%ax
  10948. movzwl %ax,%eax
  10949. Compress into:
  10950. movzbl %al,%eax
  10951. }
  10952. RegUsed := False;
  10953. case taicpu(p).opsize of
  10954. S_BW:
  10955. case taicpu(hp1).opsize of
  10956. S_WL:
  10957. begin
  10958. taicpu(p).opsize := S_BL;
  10959. RegUsed := True;
  10960. end;
  10961. {$ifdef x86_64}
  10962. S_WQ:
  10963. begin
  10964. if taicpu(p).opcode = A_MOVZX then
  10965. begin
  10966. taicpu(p).opsize := S_BL;
  10967. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10968. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10969. end
  10970. else
  10971. taicpu(p).opsize := S_BQ;
  10972. RegUsed := True;
  10973. end;
  10974. {$endif x86_64}
  10975. else
  10976. ;
  10977. end;
  10978. {$ifdef x86_64}
  10979. S_BL:
  10980. case taicpu(hp1).opsize of
  10981. S_LQ:
  10982. begin
  10983. if taicpu(p).opcode = A_MOVZX then
  10984. begin
  10985. taicpu(p).opsize := S_BL;
  10986. { 64-bit zero extension is implicit, so change to the 32-bit register }
  10987. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  10988. end
  10989. else
  10990. taicpu(p).opsize := S_BQ;
  10991. RegUsed := True;
  10992. end;
  10993. else
  10994. ;
  10995. end;
  10996. S_WL:
  10997. case taicpu(hp1).opsize of
  10998. S_LQ:
  10999. begin
  11000. if taicpu(p).opcode = A_MOVZX then
  11001. begin
  11002. taicpu(p).opsize := S_WL;
  11003. { 64-bit zero extension is implicit, so change to the 32-bit register }
  11004. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  11005. end
  11006. else
  11007. taicpu(p).opsize := S_WQ;
  11008. RegUsed := True;
  11009. end;
  11010. else
  11011. ;
  11012. end;
  11013. {$endif x86_64}
  11014. else
  11015. ;
  11016. end;
  11017. if RegUsed then
  11018. begin
  11019. DebugMsg(SPeepholeOptimization + 'MovxMovx2Movx', p);
  11020. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg;
  11021. RemoveInstruction(hp1);
  11022. Result := True;
  11023. Exit;
  11024. end;
  11025. end;
  11026. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  11027. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  11028. GetNextInstruction(hp1, hp2) and
  11029. MatchInstruction(hp2, [A_AND, A_OR, A_XOR, A_TEST], []) and
  11030. (
  11031. ((taicpu(hp2).opsize = S_W) and (taicpu(p).opsize = S_BW)) or
  11032. ((taicpu(hp2).opsize = S_L) and (taicpu(p).opsize in [S_BL, S_WL]))
  11033. {$ifdef x86_64}
  11034. or ((taicpu(hp2).opsize = S_Q) and (taicpu(p).opsize in [S_BL, S_BQ, S_WL, S_WQ, S_LQ]))
  11035. {$endif x86_64}
  11036. ) and
  11037. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  11038. (
  11039. (
  11040. (taicpu(hp2).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  11041. (taicpu(hp2).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  11042. ) or
  11043. (
  11044. { Only allow the operands in reverse order for TEST instructions }
  11045. (taicpu(hp2).opcode = A_TEST) and
  11046. (taicpu(hp2).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11047. (taicpu(hp2).oper[1]^.reg = taicpu(hp1).oper[1]^.reg)
  11048. )
  11049. ) then
  11050. begin
  11051. {
  11052. For example:
  11053. movzbl %al,%eax
  11054. movzbl (ref),%edx
  11055. andl %edx,%eax
  11056. (%edx deallocated)
  11057. Change to:
  11058. andb (ref),%al
  11059. movzbl %al,%eax
  11060. Rules are:
  11061. - First two instructions have the same opcode and opsize
  11062. - First instruction's operands are the same super-register
  11063. - Second instruction operates on a different register
  11064. - Third instruction is AND, OR, XOR or TEST
  11065. - Third instruction's operands are the destination registers of the first two instructions
  11066. - Third instruction writes to the destination register of the first instruction (except with TEST)
  11067. - Second instruction's destination register is deallocated afterwards
  11068. }
  11069. TransferUsedRegs(TmpUsedRegs);
  11070. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11071. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  11072. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs) then
  11073. begin
  11074. case taicpu(p).opsize of
  11075. S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11076. NewSize := S_B;
  11077. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11078. NewSize := S_W;
  11079. {$ifdef x86_64}
  11080. S_LQ:
  11081. NewSize := S_L;
  11082. {$endif x86_64}
  11083. else
  11084. InternalError(2021120301);
  11085. end;
  11086. taicpu(hp2).loadoper(0, taicpu(hp1).oper[0]^);
  11087. taicpu(hp2).loadreg(1, taicpu(p).oper[0]^.reg);
  11088. taicpu(hp2).opsize := NewSize;
  11089. RemoveInstruction(hp1);
  11090. { With TEST, it's best to keep the MOVX instruction at the top }
  11091. if (taicpu(hp2).opcode <> A_TEST) then
  11092. begin
  11093. DebugMsg(SPeepholeOptimization + 'MovxMovxTest2MovxTest', p);
  11094. asml.Remove(p);
  11095. { If the third instruction uses the flags, the MOVX instruction won't modify then }
  11096. asml.InsertAfter(p, hp2);
  11097. p := hp2;
  11098. end
  11099. else
  11100. DebugMsg(SPeepholeOptimization + 'MovxMovxOp2OpMovx', p);
  11101. Result := True;
  11102. Exit;
  11103. end;
  11104. end;
  11105. end;
  11106. if taicpu(p).opcode=A_MOVZX then
  11107. begin
  11108. { removes superfluous And's after movzx's }
  11109. if reg_and_hp1_is_instr and
  11110. (taicpu(hp1).opcode = A_AND) and
  11111. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11112. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  11113. {$ifdef x86_64}
  11114. { check for implicit extension to 64 bit }
  11115. or
  11116. ((taicpu(p).opsize in [S_BL,S_WL]) and
  11117. (taicpu(hp1).opsize=S_Q) and
  11118. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  11119. )
  11120. {$endif x86_64}
  11121. )
  11122. then
  11123. begin
  11124. case taicpu(p).opsize Of
  11125. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11126. if (taicpu(hp1).oper[0]^.val = $ff) then
  11127. begin
  11128. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  11129. RemoveInstruction(hp1);
  11130. Result:=true;
  11131. exit;
  11132. end;
  11133. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11134. if (taicpu(hp1).oper[0]^.val = $ffff) then
  11135. begin
  11136. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  11137. RemoveInstruction(hp1);
  11138. Result:=true;
  11139. exit;
  11140. end;
  11141. {$ifdef x86_64}
  11142. S_LQ:
  11143. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  11144. begin
  11145. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  11146. RemoveInstruction(hp1);
  11147. Result:=true;
  11148. exit;
  11149. end;
  11150. {$endif x86_64}
  11151. else
  11152. ;
  11153. end;
  11154. { we cannot get rid of the and, but can we get rid of the movz ?}
  11155. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  11156. begin
  11157. case taicpu(p).opsize Of
  11158. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  11159. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  11160. begin
  11161. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  11162. RemoveCurrentP(p,hp1);
  11163. Result:=true;
  11164. exit;
  11165. end;
  11166. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  11167. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  11168. begin
  11169. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  11170. RemoveCurrentP(p,hp1);
  11171. Result:=true;
  11172. exit;
  11173. end;
  11174. {$ifdef x86_64}
  11175. S_LQ:
  11176. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  11177. begin
  11178. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  11179. RemoveCurrentP(p,hp1);
  11180. Result:=true;
  11181. exit;
  11182. end;
  11183. {$endif x86_64}
  11184. else
  11185. ;
  11186. end;
  11187. end;
  11188. end;
  11189. { changes some movzx constructs to faster synonyms (all examples
  11190. are given with eax/ax, but are also valid for other registers)}
  11191. if MatchOpType(taicpu(p),top_reg,top_reg) then
  11192. begin
  11193. case taicpu(p).opsize of
  11194. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  11195. (the machine code is equivalent to movzbl %al,%eax), but the
  11196. code generator still generates that assembler instruction and
  11197. it is silently converted. This should probably be checked.
  11198. [Kit] }
  11199. S_BW:
  11200. begin
  11201. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  11202. (
  11203. not IsMOVZXAcceptable
  11204. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  11205. or (
  11206. (cs_opt_size in current_settings.optimizerswitches) and
  11207. (taicpu(p).oper[1]^.reg = NR_AX)
  11208. )
  11209. ) then
  11210. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  11211. begin
  11212. DebugMsg(SPeepholeOptimization + 'var7',p);
  11213. taicpu(p).opcode := A_AND;
  11214. taicpu(p).changeopsize(S_W);
  11215. taicpu(p).loadConst(0,$ff);
  11216. Result := True;
  11217. end
  11218. else if not IsMOVZXAcceptable and
  11219. GetNextInstruction(p, hp1) and
  11220. (tai(hp1).typ = ait_instruction) and
  11221. (taicpu(hp1).opcode = A_AND) and
  11222. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11223. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11224. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  11225. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  11226. begin
  11227. DebugMsg(SPeepholeOptimization + 'var8',p);
  11228. taicpu(p).opcode := A_MOV;
  11229. taicpu(p).changeopsize(S_W);
  11230. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  11231. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11232. Result := True;
  11233. end;
  11234. end;
  11235. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  11236. S_BL:
  11237. if not IsMOVZXAcceptable then
  11238. begin
  11239. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  11240. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  11241. begin
  11242. DebugMsg(SPeepholeOptimization + 'var9',p);
  11243. taicpu(p).opcode := A_AND;
  11244. taicpu(p).changeopsize(S_L);
  11245. taicpu(p).loadConst(0,$ff);
  11246. Result := True;
  11247. end
  11248. else if GetNextInstruction(p, hp1) and
  11249. (tai(hp1).typ = ait_instruction) and
  11250. (taicpu(hp1).opcode = A_AND) and
  11251. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11252. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11253. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  11254. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  11255. begin
  11256. DebugMsg(SPeepholeOptimization + 'var10',p);
  11257. taicpu(p).opcode := A_MOV;
  11258. taicpu(p).changeopsize(S_L);
  11259. { do not use R_SUBWHOLE
  11260. as movl %rdx,%eax
  11261. is invalid in assembler PM }
  11262. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11263. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11264. Result := True;
  11265. end;
  11266. end;
  11267. {$endif i8086}
  11268. S_WL:
  11269. if not IsMOVZXAcceptable then
  11270. begin
  11271. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  11272. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  11273. begin
  11274. DebugMsg(SPeepholeOptimization + 'var11',p);
  11275. taicpu(p).opcode := A_AND;
  11276. taicpu(p).changeopsize(S_L);
  11277. taicpu(p).loadConst(0,$ffff);
  11278. Result := True;
  11279. end
  11280. else if GetNextInstruction(p, hp1) and
  11281. (tai(hp1).typ = ait_instruction) and
  11282. (taicpu(hp1).opcode = A_AND) and
  11283. (taicpu(hp1).oper[0]^.typ = top_const) and
  11284. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11285. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11286. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  11287. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  11288. begin
  11289. DebugMsg(SPeepholeOptimization + 'var12',p);
  11290. taicpu(p).opcode := A_MOV;
  11291. taicpu(p).changeopsize(S_L);
  11292. { do not use R_SUBWHOLE
  11293. as movl %rdx,%eax
  11294. is invalid in assembler PM }
  11295. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  11296. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  11297. Result := True;
  11298. end;
  11299. end;
  11300. else
  11301. InternalError(2017050705);
  11302. end;
  11303. end
  11304. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  11305. begin
  11306. if GetNextInstruction(p, hp1) and
  11307. (tai(hp1).typ = ait_instruction) and
  11308. (taicpu(hp1).opcode = A_AND) and
  11309. MatchOpType(taicpu(hp1),top_const,top_reg) and
  11310. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  11311. begin
  11312. //taicpu(p).opcode := A_MOV;
  11313. case taicpu(p).opsize Of
  11314. S_BL:
  11315. begin
  11316. DebugMsg(SPeepholeOptimization + 'var13',p);
  11317. taicpu(hp1).changeopsize(S_L);
  11318. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11319. end;
  11320. S_WL:
  11321. begin
  11322. DebugMsg(SPeepholeOptimization + 'var14',p);
  11323. taicpu(hp1).changeopsize(S_L);
  11324. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  11325. end;
  11326. S_BW:
  11327. begin
  11328. DebugMsg(SPeepholeOptimization + 'var15',p);
  11329. taicpu(hp1).changeopsize(S_W);
  11330. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  11331. end;
  11332. else
  11333. Internalerror(2017050704)
  11334. end;
  11335. Result := True;
  11336. end;
  11337. end;
  11338. end;
  11339. end;
  11340. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  11341. var
  11342. hp1, hp2 : tai;
  11343. MaskLength : Cardinal;
  11344. MaskedBits : TCgInt;
  11345. ActiveReg : TRegister;
  11346. begin
  11347. Result:=false;
  11348. { There are no optimisations for reference targets }
  11349. if (taicpu(p).oper[1]^.typ <> top_reg) then
  11350. Exit;
  11351. while GetNextInstruction(p, hp1) and
  11352. (hp1.typ = ait_instruction) do
  11353. begin
  11354. if (taicpu(p).oper[0]^.typ = top_const) then
  11355. begin
  11356. case taicpu(hp1).opcode of
  11357. A_AND:
  11358. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11359. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  11360. { the second register must contain the first one, so compare their subreg types }
  11361. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  11362. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  11363. { change
  11364. and const1, reg
  11365. and const2, reg
  11366. to
  11367. and (const1 and const2), reg
  11368. }
  11369. begin
  11370. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  11371. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  11372. RemoveCurrentP(p, hp1);
  11373. Result:=true;
  11374. exit;
  11375. end;
  11376. A_CMP:
  11377. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  11378. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  11379. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  11380. { Just check that the condition on the next instruction is compatible }
  11381. GetNextInstruction(hp1, hp2) and
  11382. (hp2.typ = ait_instruction) and
  11383. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  11384. then
  11385. { change
  11386. and 2^n, reg
  11387. cmp 2^n, reg
  11388. j(c) / set(c) / cmov(c) (c is equal or not equal)
  11389. to
  11390. and 2^n, reg
  11391. test reg, reg
  11392. j(~c) / set(~c) / cmov(~c)
  11393. }
  11394. begin
  11395. { Keep TEST instruction in, rather than remove it, because
  11396. it may trigger other optimisations such as MovAndTest2Test }
  11397. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  11398. taicpu(hp1).opcode := A_TEST;
  11399. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  11400. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  11401. Result := True;
  11402. Exit;
  11403. end;
  11404. A_MOVZX:
  11405. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  11406. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  11407. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  11408. (
  11409. (
  11410. (taicpu(p).opsize=S_W) and
  11411. (taicpu(hp1).opsize=S_BW)
  11412. ) or
  11413. (
  11414. (taicpu(p).opsize=S_L) and
  11415. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  11416. )
  11417. {$ifdef x86_64}
  11418. or
  11419. (
  11420. (taicpu(p).opsize=S_Q) and
  11421. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  11422. )
  11423. {$endif x86_64}
  11424. ) then
  11425. begin
  11426. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  11427. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  11428. ) or
  11429. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  11430. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  11431. then
  11432. begin
  11433. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  11434. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  11435. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  11436. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  11437. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  11438. }
  11439. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  11440. RemoveInstruction(hp1);
  11441. { See if there are other optimisations possible }
  11442. Continue;
  11443. end;
  11444. end;
  11445. A_SHL:
  11446. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11447. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  11448. begin
  11449. {$ifopt R+}
  11450. {$define RANGE_WAS_ON}
  11451. {$R-}
  11452. {$endif}
  11453. { get length of potential and mask }
  11454. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  11455. { really a mask? }
  11456. {$ifdef RANGE_WAS_ON}
  11457. {$R+}
  11458. {$endif}
  11459. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  11460. { unmasked part shifted out? }
  11461. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  11462. begin
  11463. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  11464. RemoveCurrentP(p, hp1);
  11465. Result:=true;
  11466. exit;
  11467. end;
  11468. end;
  11469. A_SHR:
  11470. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  11471. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  11472. (taicpu(hp1).oper[0]^.val <= 63) then
  11473. begin
  11474. { Does SHR combined with the AND cover all the bits?
  11475. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  11476. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  11477. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  11478. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  11479. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  11480. begin
  11481. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  11482. RemoveCurrentP(p, hp1);
  11483. Result := True;
  11484. Exit;
  11485. end;
  11486. end;
  11487. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11488. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  11489. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  11490. begin
  11491. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11492. (
  11493. (
  11494. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  11495. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  11496. ) or (
  11497. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  11498. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  11499. {$ifdef x86_64}
  11500. ) or (
  11501. (taicpu(hp1).opsize = S_LQ) and
  11502. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  11503. {$endif x86_64}
  11504. )
  11505. ) then
  11506. begin
  11507. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  11508. begin
  11509. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  11510. RemoveInstruction(hp1);
  11511. { See if there are other optimisations possible }
  11512. Continue;
  11513. end;
  11514. { The super-registers are the same though.
  11515. Note that this change by itself doesn't improve
  11516. code speed, but it opens up other optimisations. }
  11517. {$ifdef x86_64}
  11518. { Convert 64-bit register to 32-bit }
  11519. case taicpu(hp1).opsize of
  11520. S_BQ:
  11521. begin
  11522. taicpu(hp1).opsize := S_BL;
  11523. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  11524. end;
  11525. S_WQ:
  11526. begin
  11527. taicpu(hp1).opsize := S_WL;
  11528. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  11529. end
  11530. else
  11531. ;
  11532. end;
  11533. {$endif x86_64}
  11534. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  11535. taicpu(hp1).opcode := A_MOVZX;
  11536. { See if there are other optimisations possible }
  11537. Continue;
  11538. end;
  11539. end;
  11540. else
  11541. ;
  11542. end;
  11543. end
  11544. else if MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^.reg) and
  11545. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  11546. begin
  11547. {$ifdef x86_64}
  11548. if (taicpu(p).opsize = S_Q) then
  11549. begin
  11550. { Never necessary }
  11551. DebugMsg(SPeepholeOptimization + 'Andq2Nop', p);
  11552. RemoveCurrentP(p, hp1);
  11553. Result := True;
  11554. Exit;
  11555. end;
  11556. {$endif x86_64}
  11557. { Forward check to determine necessity of and %reg,%reg }
  11558. TransferUsedRegs(TmpUsedRegs);
  11559. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  11560. { Saves on a bunch of dereferences }
  11561. ActiveReg := taicpu(p).oper[1]^.reg;
  11562. case taicpu(hp1).opcode of
  11563. A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  11564. if (
  11565. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11566. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11567. ) and
  11568. (
  11569. (taicpu(hp1).opcode <> A_MOV) or
  11570. (taicpu(hp1).oper[1]^.typ <> top_ref) or
  11571. not RegInRef(ActiveReg, taicpu(hp1).oper[1]^.ref^)
  11572. ) and
  11573. not (
  11574. { If mov %reg,%reg is present, remove that instruction instead in OptPass1MOV }
  11575. (taicpu(hp1).opcode = A_MOV) and
  11576. MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) and
  11577. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg)
  11578. ) and
  11579. (
  11580. (
  11581. (taicpu(hp1).oper[0]^.typ = top_reg) and
  11582. (taicpu(hp1).oper[0]^.reg = ActiveReg) and
  11583. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg)
  11584. ) or
  11585. (
  11586. {$ifdef x86_64}
  11587. (
  11588. { If we read from the register, make sure it's not dependent on the upper 32 bits }
  11589. (taicpu(hp1).oper[0]^.typ <> top_reg) or
  11590. not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ActiveReg) or
  11591. (GetSubReg(taicpu(hp1).oper[0]^.reg) <> R_SUBQ)
  11592. ) and
  11593. {$endif x86_64}
  11594. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs)
  11595. )
  11596. ) then
  11597. begin
  11598. DebugMsg(SPeepholeOptimization + 'AndMovx2Movx', p);
  11599. RemoveCurrentP(p, hp1);
  11600. Result := True;
  11601. Exit;
  11602. end;
  11603. A_ADD,
  11604. A_AND,
  11605. A_BSF,
  11606. A_BSR,
  11607. A_BTC,
  11608. A_BTR,
  11609. A_BTS,
  11610. A_OR,
  11611. A_SUB,
  11612. A_XOR:
  11613. { Register is written to, so this will clear the upper 32 bits (2-operand instructions) }
  11614. if (
  11615. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11616. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11617. ) and
  11618. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) then
  11619. begin
  11620. DebugMsg(SPeepholeOptimization + 'AndOp2Op 2', p);
  11621. RemoveCurrentP(p, hp1);
  11622. Result := True;
  11623. Exit;
  11624. end;
  11625. A_CMP,
  11626. A_TEST:
  11627. if (
  11628. (taicpu(hp1).oper[0]^.typ <> top_ref) or
  11629. not RegInRef(ActiveReg, taicpu(hp1).oper[0]^.ref^)
  11630. ) and
  11631. MatchOperand(taicpu(hp1).oper[1]^, ActiveReg) and
  11632. not RegUsedAfterInstruction(ActiveReg, hp1, TmpUsedRegs) then
  11633. begin
  11634. DebugMsg(SPeepholeOptimization + 'AND; CMP/TEST -> CMP/TEST', p);
  11635. RemoveCurrentP(p, hp1);
  11636. Result := True;
  11637. Exit;
  11638. end;
  11639. A_BSWAP,
  11640. A_NEG,
  11641. A_NOT:
  11642. { Register is written to, so this will clear the upper 32 bits (1-operand instructions) }
  11643. if MatchOperand(taicpu(hp1).oper[0]^, ActiveReg) then
  11644. begin
  11645. DebugMsg(SPeepholeOptimization + 'AndOp2Op 1', p);
  11646. RemoveCurrentP(p, hp1);
  11647. Result := True;
  11648. Exit;
  11649. end;
  11650. else
  11651. ;
  11652. end;
  11653. end;
  11654. if (taicpu(hp1).is_jmp) and
  11655. (taicpu(hp1).opcode<>A_JMP) and
  11656. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  11657. begin
  11658. { change
  11659. and x, reg
  11660. jxx
  11661. to
  11662. test x, reg
  11663. jxx
  11664. if reg is deallocated before the
  11665. jump, but only if it's a conditional jump (PFV)
  11666. }
  11667. DebugMsg(SPeepholeOptimization + 'AndJcc2TestJcc', p);
  11668. taicpu(p).opcode := A_TEST;
  11669. Exit;
  11670. end;
  11671. Break;
  11672. end;
  11673. { Lone AND tests }
  11674. if (taicpu(p).oper[0]^.typ = top_const) then
  11675. begin
  11676. {
  11677. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  11678. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  11679. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  11680. }
  11681. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  11682. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  11683. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  11684. begin
  11685. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  11686. if taicpu(p).opsize = S_L then
  11687. begin
  11688. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  11689. Result := True;
  11690. end;
  11691. end;
  11692. end;
  11693. { Backward check to determine necessity of and %reg,%reg }
  11694. if (taicpu(p).oper[0]^.typ = top_reg) and
  11695. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  11696. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  11697. GetLastInstruction(p, hp2) and
  11698. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  11699. { Check size of adjacent instruction to determine if the AND is
  11700. effectively a null operation }
  11701. (
  11702. (taicpu(p).opsize = taicpu(hp2).opsize) or
  11703. { Note: Don't include S_Q }
  11704. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  11705. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  11706. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  11707. ) then
  11708. begin
  11709. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  11710. { If GetNextInstruction returned False, hp1 will be nil }
  11711. RemoveCurrentP(p, hp1);
  11712. Result := True;
  11713. Exit;
  11714. end;
  11715. end;
  11716. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  11717. var
  11718. hp1, hp2: tai;
  11719. NewRef: TReference;
  11720. Distance: Cardinal;
  11721. TempTracking: TAllUsedRegs;
  11722. { This entire nested function is used in an if-statement below, but we
  11723. want to avoid all the used reg transfers and GetNextInstruction calls
  11724. until we really have to check }
  11725. function MemRegisterNotUsedLater: Boolean; inline;
  11726. var
  11727. hp2: tai;
  11728. begin
  11729. TransferUsedRegs(TmpUsedRegs);
  11730. hp2 := p;
  11731. repeat
  11732. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11733. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11734. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  11735. end;
  11736. begin
  11737. Result := False;
  11738. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  11739. (taicpu(p).oper[1]^.typ = top_reg) then
  11740. begin
  11741. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  11742. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  11743. (hp1.typ <> ait_instruction) or
  11744. not
  11745. (
  11746. (cs_opt_level3 in current_settings.optimizerswitches) or
  11747. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  11748. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  11749. ) then
  11750. Exit;
  11751. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  11752. addq $x, %rax
  11753. movq %rax, %rdx
  11754. sarq $63, %rdx
  11755. (%rax still in use)
  11756. ...letting OptPass2ADD run its course (and without -Os) will produce:
  11757. leaq $x(%rax),%rdx
  11758. addq $x, %rax
  11759. sarq $63, %rdx
  11760. ...which is okay since it breaks the dependency chain between
  11761. addq and movq, but if OptPass2MOV is called first:
  11762. addq $x, %rax
  11763. cqto
  11764. ...which is better in all ways, taking only 2 cycles to execute
  11765. and much smaller in code size.
  11766. }
  11767. { The extra register tracking is quite strenuous }
  11768. if (cs_opt_level2 in current_settings.optimizerswitches) and
  11769. MatchInstruction(hp1, A_MOV, []) then
  11770. begin
  11771. { Update the register tracking to the MOV instruction }
  11772. CopyUsedRegs(TempTracking);
  11773. hp2 := p;
  11774. repeat
  11775. UpdateUsedRegs(tai(hp2.Next));
  11776. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11777. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  11778. OptPass2ADD get called again }
  11779. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  11780. begin
  11781. { Reset the tracking to the current instruction }
  11782. RestoreUsedRegs(TempTracking);
  11783. ReleaseUsedRegs(TempTracking);
  11784. Result := True;
  11785. Exit;
  11786. end;
  11787. { Reset the tracking to the current instruction }
  11788. RestoreUsedRegs(TempTracking);
  11789. ReleaseUsedRegs(TempTracking);
  11790. { If OptPass2MOV returned True, we don't need to set Result to
  11791. True if hp1 didn't change because the ADD instruction didn't
  11792. get modified and we'll be evaluating hp1 again when the
  11793. peephole optimizer reaches it }
  11794. end;
  11795. { Change:
  11796. add %reg2,%reg1
  11797. (%reg2 not modified in between)
  11798. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  11799. To:
  11800. mov/s/z #(%reg1,%reg2),%reg1
  11801. }
  11802. if (taicpu(p).oper[0]^.typ = top_reg) and
  11803. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  11804. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  11805. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  11806. (
  11807. (
  11808. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  11809. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  11810. { r/esp cannot be an index }
  11811. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  11812. ) or (
  11813. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  11814. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  11815. )
  11816. ) and (
  11817. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  11818. (
  11819. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  11820. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  11821. MemRegisterNotUsedLater
  11822. )
  11823. ) then
  11824. begin
  11825. if (
  11826. { Instructions are guaranteed to be adjacent on -O2 and under }
  11827. (cs_opt_level3 in current_settings.optimizerswitches) and
  11828. RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp1)
  11829. ) then
  11830. begin
  11831. { If the other register is used in between, move the MOV
  11832. instruction to right after the ADD instruction so a
  11833. saving can still be made }
  11834. Asml.Remove(hp1);
  11835. Asml.InsertAfter(hp1, p);
  11836. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11837. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11838. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done (instruction moved)', p);
  11839. RemoveCurrentp(p, hp1);
  11840. end
  11841. else
  11842. begin
  11843. AllocRegBetween(taicpu(p).oper[0]^.reg, p, hp1, UsedRegs);
  11844. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  11845. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  11846. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  11847. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11848. { hp1 may not be the immediate next instruction under -O3 }
  11849. RemoveCurrentp(p)
  11850. else
  11851. RemoveCurrentp(p, hp1);
  11852. end;
  11853. Result := True;
  11854. Exit;
  11855. end;
  11856. { Change:
  11857. addl/q $x,%reg1
  11858. movl/q %reg1,%reg2
  11859. To:
  11860. leal/q $x(%reg1),%reg2
  11861. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  11862. Breaks the dependency chain.
  11863. }
  11864. if (taicpu(p).oper[0]^.typ = top_const) and
  11865. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  11866. (taicpu(hp1).oper[1]^.typ = top_reg) and
  11867. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  11868. (
  11869. { Instructions are guaranteed to be adjacent on -O2 and under }
  11870. not (cs_opt_level3 in current_settings.optimizerswitches) or
  11871. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  11872. ) then
  11873. begin
  11874. TransferUsedRegs(TmpUsedRegs);
  11875. hp2 := p;
  11876. repeat
  11877. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  11878. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  11879. if (
  11880. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  11881. not (cs_opt_size in current_settings.optimizerswitches) or
  11882. (
  11883. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  11884. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  11885. )
  11886. ) then
  11887. begin
  11888. { Change the MOV instruction to a LEA instruction, and update the
  11889. first operand }
  11890. reference_reset(NewRef, 1, []);
  11891. NewRef.base := taicpu(p).oper[1]^.reg;
  11892. NewRef.scalefactor := 1;
  11893. NewRef.offset := asizeint(taicpu(p).oper[0]^.val);
  11894. taicpu(hp1).opcode := A_LEA;
  11895. taicpu(hp1).loadref(0, NewRef);
  11896. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  11897. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  11898. begin
  11899. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  11900. { Move what is now the LEA instruction to before the ADD instruction }
  11901. Asml.Remove(hp1);
  11902. Asml.InsertBefore(hp1, p);
  11903. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  11904. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  11905. p := hp1;
  11906. end
  11907. else
  11908. begin
  11909. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  11910. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', hp1);
  11911. if (cs_opt_level3 in current_settings.optimizerswitches) then
  11912. { hp1 may not be the immediate next instruction under -O3 }
  11913. RemoveCurrentp(p)
  11914. else
  11915. RemoveCurrentp(p, hp1);
  11916. end;
  11917. Result := True;
  11918. end;
  11919. end;
  11920. end;
  11921. end;
  11922. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  11923. var
  11924. SubReg: TSubRegister;
  11925. begin
  11926. Result:=false;
  11927. SubReg := getsubreg(taicpu(p).oper[1]^.reg);
  11928. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  11929. with taicpu(p).oper[0]^.ref^ do
  11930. if (offset = 0) and not Assigned(symbol) and not Assigned(relsymbol) and (index <> NR_NO) then
  11931. begin
  11932. if (scalefactor <= 1) and SuperRegistersEqual(base, taicpu(p).oper[1]^.reg) then
  11933. begin
  11934. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(index), SubReg));
  11935. taicpu(p).opcode := A_ADD;
  11936. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  11937. Result := True;
  11938. end
  11939. else if SuperRegistersEqual(index, taicpu(p).oper[1]^.reg) then
  11940. begin
  11941. if (base <> NR_NO) then
  11942. begin
  11943. if (scalefactor <= 1) then
  11944. begin
  11945. taicpu(p).loadreg(0, newreg(R_INTREGISTER, getsupreg(base), SubReg));
  11946. taicpu(p).opcode := A_ADD;
  11947. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  11948. Result := True;
  11949. end;
  11950. end
  11951. else
  11952. { Convert lea (%reg,2^x),%reg to shl x,%reg }
  11953. if (scalefactor in [2, 4, 8]) then
  11954. begin
  11955. { BsrByte is, in essence, the base-2 logarithm of the scale factor }
  11956. taicpu(p).loadconst(0, BsrByte(scalefactor));
  11957. taicpu(p).opcode := A_SHL;
  11958. DebugMsg(SPeepholeOptimization + 'Lea2Shl done',p);
  11959. Result := True;
  11960. end;
  11961. end;
  11962. end;
  11963. end;
  11964. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  11965. var
  11966. hp1, hp2: tai;
  11967. NewRef: TReference;
  11968. Distance: Cardinal;
  11969. TempTracking: TAllUsedRegs;
  11970. begin
  11971. Result := False;
  11972. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) and
  11973. MatchOpType(taicpu(p),top_const,top_reg) then
  11974. begin
  11975. Distance := GetNextInstructionUsingRegCount(p, hp1, taicpu(p).oper[1]^.reg);
  11976. if (Distance = 0) or (Distance > 3) { Likely too far to make a meaningful difference } or
  11977. (hp1.typ <> ait_instruction) or
  11978. not
  11979. (
  11980. (cs_opt_level3 in current_settings.optimizerswitches) or
  11981. { GetNextInstructionUsingRegCount just returns the next valid instruction under -O2 and under }
  11982. RegInInstruction(taicpu(p).oper[1]^.reg, hp1)
  11983. ) then
  11984. Exit;
  11985. { Some of the MOV optimisations are much more in-depth. For example, if we have:
  11986. subq $x, %rax
  11987. movq %rax, %rdx
  11988. sarq $63, %rdx
  11989. (%rax still in use)
  11990. ...letting OptPass2SUB run its course (and without -Os) will produce:
  11991. leaq $-x(%rax),%rdx
  11992. movq $x, %rax
  11993. sarq $63, %rdx
  11994. ...which is okay since it breaks the dependency chain between
  11995. subq and movq, but if OptPass2MOV is called first:
  11996. subq $x, %rax
  11997. cqto
  11998. ...which is better in all ways, taking only 2 cycles to execute
  11999. and much smaller in code size.
  12000. }
  12001. { The extra register tracking is quite strenuous }
  12002. if (cs_opt_level2 in current_settings.optimizerswitches) and
  12003. MatchInstruction(hp1, A_MOV, []) then
  12004. begin
  12005. { Update the register tracking to the MOV instruction }
  12006. CopyUsedRegs(TempTracking);
  12007. hp2 := p;
  12008. repeat
  12009. UpdateUsedRegs(tai(hp2.Next));
  12010. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12011. { if hp1 <> hp2 after the call, then hp1 got removed, so let
  12012. OptPass2SUB get called again }
  12013. if OptPass2MOV(hp1) and (hp1 <> hp2) then
  12014. begin
  12015. { Reset the tracking to the current instruction }
  12016. RestoreUsedRegs(TempTracking);
  12017. ReleaseUsedRegs(TempTracking);
  12018. Result := True;
  12019. Exit;
  12020. end;
  12021. { Reset the tracking to the current instruction }
  12022. RestoreUsedRegs(TempTracking);
  12023. ReleaseUsedRegs(TempTracking);
  12024. { If OptPass2MOV returned True, we don't need to set Result to
  12025. True if hp1 didn't change because the SUB instruction didn't
  12026. get modified and we'll be evaluating hp1 again when the
  12027. peephole optimizer reaches it }
  12028. end;
  12029. { Change:
  12030. subl/q $x,%reg1
  12031. movl/q %reg1,%reg2
  12032. To:
  12033. leal/q $-x(%reg1),%reg2
  12034. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  12035. Breaks the dependency chain and potentially permits the removal of
  12036. a CMP instruction if one follows.
  12037. }
  12038. if MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  12039. (taicpu(hp1).oper[1]^.typ = top_reg) and
  12040. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  12041. (
  12042. { Instructions are guaranteed to be adjacent on -O2 and under }
  12043. not (cs_opt_level3 in current_settings.optimizerswitches) or
  12044. not RegUsedBetween(taicpu(hp1).oper[1]^.reg, p, hp1)
  12045. ) then
  12046. begin
  12047. TransferUsedRegs(TmpUsedRegs);
  12048. hp2 := p;
  12049. repeat
  12050. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12051. until not (cs_opt_level3 in current_settings.optimizerswitches) or not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12052. if (
  12053. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  12054. not (cs_opt_size in current_settings.optimizerswitches) or
  12055. (
  12056. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  12057. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  12058. )
  12059. ) then
  12060. begin
  12061. { Change the MOV instruction to a LEA instruction, and update the
  12062. first operand }
  12063. reference_reset(NewRef, 1, []);
  12064. NewRef.base := taicpu(p).oper[1]^.reg;
  12065. NewRef.scalefactor := 1;
  12066. NewRef.offset := -taicpu(p).oper[0]^.val;
  12067. taicpu(hp1).opcode := A_LEA;
  12068. taicpu(hp1).loadref(0, NewRef);
  12069. TransferUsedRegs(TmpUsedRegs);
  12070. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12071. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  12072. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12073. begin
  12074. hp2 := tai(hp1.Next); { for the benefit of AllocRegBetween }
  12075. { Move what is now the LEA instruction to before the SUB instruction }
  12076. Asml.Remove(hp1);
  12077. Asml.InsertBefore(hp1, p);
  12078. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  12079. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  12080. p := hp1;
  12081. end
  12082. else
  12083. begin
  12084. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  12085. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', hp1);
  12086. if (cs_opt_level3 in current_settings.optimizerswitches) then
  12087. { hp1 may not be the immediate next instruction under -O3 }
  12088. RemoveCurrentp(p)
  12089. else
  12090. RemoveCurrentp(p, hp1);
  12091. end;
  12092. Result := True;
  12093. end;
  12094. end;
  12095. end;
  12096. end;
  12097. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  12098. begin
  12099. { we can skip all instructions not messing with the stack pointer }
  12100. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  12101. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  12102. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  12103. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  12104. ({(taicpu(hp1).ops=0) or }
  12105. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  12106. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  12107. ) and }
  12108. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  12109. )
  12110. ) do
  12111. GetNextInstruction(hp1,hp1);
  12112. Result:=assigned(hp1);
  12113. end;
  12114. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  12115. var
  12116. hp1, hp2, hp3, hp4, hp5: tai;
  12117. begin
  12118. Result:=false;
  12119. hp5:=nil;
  12120. { replace
  12121. leal(q) x(<stackpointer>),<stackpointer>
  12122. call procname
  12123. leal(q) -x(<stackpointer>),<stackpointer>
  12124. ret
  12125. by
  12126. jmp procname
  12127. but do it only on level 4 because it destroys stack back traces
  12128. }
  12129. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12130. MatchOpType(taicpu(p),top_ref,top_reg) and
  12131. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  12132. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  12133. { the -8 or -24 are not required, but bail out early if possible,
  12134. higher values are unlikely }
  12135. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  12136. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  12137. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  12138. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  12139. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  12140. GetNextInstruction(p, hp1) and
  12141. { Take a copy of hp1 }
  12142. SetAndTest(hp1, hp4) and
  12143. { trick to skip label }
  12144. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  12145. SkipSimpleInstructions(hp1) and
  12146. MatchInstruction(hp1,A_CALL,[S_NO]) and
  12147. GetNextInstruction(hp1, hp2) and
  12148. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  12149. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  12150. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  12151. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  12152. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  12153. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  12154. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  12155. { Segment register will be NR_NO }
  12156. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  12157. GetNextInstruction(hp2, hp3) and
  12158. { trick to skip label }
  12159. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  12160. (MatchInstruction(hp3,A_RET,[S_NO]) or
  12161. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  12162. SetAndTest(hp3,hp5) and
  12163. GetNextInstruction(hp3,hp3) and
  12164. MatchInstruction(hp3,A_RET,[S_NO])
  12165. )
  12166. ) and
  12167. (taicpu(hp3).ops=0) then
  12168. begin
  12169. taicpu(hp1).opcode := A_JMP;
  12170. taicpu(hp1).is_jmp := true;
  12171. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  12172. RemoveCurrentP(p, hp4);
  12173. RemoveInstruction(hp2);
  12174. RemoveInstruction(hp3);
  12175. if Assigned(hp5) then
  12176. begin
  12177. AsmL.Remove(hp5);
  12178. ASmL.InsertBefore(hp5,hp1)
  12179. end;
  12180. Result:=true;
  12181. end;
  12182. end;
  12183. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  12184. {$ifdef x86_64}
  12185. var
  12186. hp1, hp2, hp3, hp4, hp5: tai;
  12187. {$endif x86_64}
  12188. begin
  12189. Result:=false;
  12190. {$ifdef x86_64}
  12191. hp5:=nil;
  12192. { replace
  12193. push %rax
  12194. call procname
  12195. pop %rcx
  12196. ret
  12197. by
  12198. jmp procname
  12199. but do it only on level 4 because it destroys stack back traces
  12200. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  12201. for all supported calling conventions
  12202. }
  12203. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12204. MatchOpType(taicpu(p),top_reg) and
  12205. (taicpu(p).oper[0]^.reg=NR_RAX) and
  12206. GetNextInstruction(p, hp1) and
  12207. { Take a copy of hp1 }
  12208. SetAndTest(hp1, hp4) and
  12209. { trick to skip label }
  12210. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  12211. SkipSimpleInstructions(hp1) and
  12212. MatchInstruction(hp1,A_CALL,[S_NO]) and
  12213. GetNextInstruction(hp1, hp2) and
  12214. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  12215. MatchOpType(taicpu(hp2),top_reg) and
  12216. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  12217. GetNextInstruction(hp2, hp3) and
  12218. { trick to skip label }
  12219. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  12220. (MatchInstruction(hp3,A_RET,[S_NO]) or
  12221. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  12222. SetAndTest(hp3,hp5) and
  12223. GetNextInstruction(hp3,hp3) and
  12224. MatchInstruction(hp3,A_RET,[S_NO])
  12225. )
  12226. ) and
  12227. (taicpu(hp3).ops=0) then
  12228. begin
  12229. taicpu(hp1).opcode := A_JMP;
  12230. taicpu(hp1).is_jmp := true;
  12231. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  12232. RemoveCurrentP(p, hp4);
  12233. RemoveInstruction(hp2);
  12234. RemoveInstruction(hp3);
  12235. if Assigned(hp5) then
  12236. begin
  12237. AsmL.Remove(hp5);
  12238. ASmL.InsertBefore(hp5,hp1)
  12239. end;
  12240. Result:=true;
  12241. end;
  12242. {$endif x86_64}
  12243. end;
  12244. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  12245. var
  12246. Value, RegName: string;
  12247. begin
  12248. Result:=false;
  12249. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  12250. begin
  12251. case taicpu(p).oper[0]^.val of
  12252. 0:
  12253. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  12254. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12255. begin
  12256. { change "mov $0,%reg" into "xor %reg,%reg" }
  12257. taicpu(p).opcode := A_XOR;
  12258. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  12259. Result := True;
  12260. {$ifdef x86_64}
  12261. end
  12262. else if (taicpu(p).opsize = S_Q) then
  12263. begin
  12264. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  12265. { The actual optimization }
  12266. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12267. taicpu(p).changeopsize(S_L);
  12268. DebugMsg(SPeepholeOptimization + 'movq $0,' + RegName + ' -> movl $0,' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  12269. Result := True;
  12270. end;
  12271. $1..$FFFFFFFF:
  12272. begin
  12273. { Code size reduction by J. Gareth "Kit" Moreton }
  12274. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  12275. case taicpu(p).opsize of
  12276. S_Q:
  12277. begin
  12278. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  12279. Value := debug_tostr(taicpu(p).oper[0]^.val);
  12280. { The actual optimization }
  12281. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  12282. taicpu(p).changeopsize(S_L);
  12283. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  12284. Result := True;
  12285. end;
  12286. else
  12287. { Do nothing };
  12288. end;
  12289. {$endif x86_64}
  12290. end;
  12291. -1:
  12292. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  12293. if (cs_opt_size in current_settings.optimizerswitches) and
  12294. (taicpu(p).opsize <> S_B) and
  12295. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  12296. begin
  12297. { change "mov $-1,%reg" into "or $-1,%reg" }
  12298. { NOTES:
  12299. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  12300. - This operation creates a false dependency on the register, so only do it when optimising for size
  12301. - 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
  12302. }
  12303. taicpu(p).opcode := A_OR;
  12304. Result := True;
  12305. end;
  12306. else
  12307. { Do nothing };
  12308. end;
  12309. end;
  12310. end;
  12311. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  12312. var
  12313. hp1: tai;
  12314. begin
  12315. { Detect:
  12316. andw x, %ax (0 <= x < $8000)
  12317. ...
  12318. movzwl %ax,%eax
  12319. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  12320. }
  12321. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  12322. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  12323. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  12324. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  12325. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  12326. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  12327. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  12328. begin
  12329. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  12330. taicpu(hp1).opcode := A_CWDE;
  12331. taicpu(hp1).clearop(0);
  12332. taicpu(hp1).clearop(1);
  12333. taicpu(hp1).ops := 0;
  12334. { A change was made, but not with p, so move forward 1 }
  12335. p := tai(p.Next);
  12336. Result := True;
  12337. end;
  12338. end;
  12339. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  12340. begin
  12341. Result := False;
  12342. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  12343. Exit;
  12344. { Convert:
  12345. movswl %ax,%eax -> cwtl
  12346. movslq %eax,%rax -> cdqe
  12347. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  12348. refer to the same opcode and depends only on the assembler's
  12349. current operand-size attribute. [Kit]
  12350. }
  12351. with taicpu(p) do
  12352. case opsize of
  12353. S_WL:
  12354. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  12355. begin
  12356. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  12357. opcode := A_CWDE;
  12358. clearop(0);
  12359. clearop(1);
  12360. ops := 0;
  12361. Result := True;
  12362. end;
  12363. {$ifdef x86_64}
  12364. S_LQ:
  12365. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  12366. begin
  12367. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  12368. opcode := A_CDQE;
  12369. clearop(0);
  12370. clearop(1);
  12371. ops := 0;
  12372. Result := True;
  12373. end;
  12374. {$endif x86_64}
  12375. else
  12376. ;
  12377. end;
  12378. end;
  12379. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  12380. var
  12381. hp1, hp2: tai;
  12382. IdentityMask, Shift: TCGInt;
  12383. LimitSize: Topsize;
  12384. DoNotMerge: Boolean;
  12385. begin
  12386. Result := False;
  12387. { All these optimisations work on "shr const,%reg" }
  12388. if not MatchOpType(taicpu(p), top_const, top_reg) then
  12389. Exit;
  12390. DoNotMerge := False;
  12391. Shift := taicpu(p).oper[0]^.val;
  12392. LimitSize := taicpu(p).opsize;
  12393. hp1 := p;
  12394. repeat
  12395. if not GetNextInstructionUsingReg(hp1, hp1, taicpu(p).oper[1]^.reg) or (hp1.typ <> ait_instruction) then
  12396. Break;
  12397. { Detect:
  12398. shr x, %reg
  12399. and y, %reg
  12400. If and y, %reg doesn't actually change the value of %reg (e.g. with
  12401. "shrl $24,%reg; andl $255,%reg", remove the AND instruction.
  12402. }
  12403. case taicpu(hp1).opcode of
  12404. A_AND:
  12405. if (taicpu(hp1).opsize = taicpu(p).opsize) and
  12406. MatchOpType(taicpu(hp1), top_const, top_reg) and
  12407. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  12408. begin
  12409. { Make sure the FLAGS register isn't in use }
  12410. TransferUsedRegs(TmpUsedRegs);
  12411. hp2 := p;
  12412. repeat
  12413. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  12414. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  12415. if not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  12416. begin
  12417. { Generate the identity mask }
  12418. case taicpu(p).opsize of
  12419. S_B:
  12420. IdentityMask := $FF shr Shift;
  12421. S_W:
  12422. IdentityMask := $FFFF shr Shift;
  12423. S_L:
  12424. IdentityMask := $FFFFFFFF shr Shift;
  12425. {$ifdef x86_64}
  12426. S_Q:
  12427. { We need to force the operands to be unsigned 64-bit
  12428. integers otherwise the wrong value is generated }
  12429. IdentityMask := TCGInt(QWord($FFFFFFFFFFFFFFFF) shr QWord(Shift));
  12430. {$endif x86_64}
  12431. else
  12432. InternalError(2022081501);
  12433. end;
  12434. if (taicpu(hp1).oper[0]^.val and IdentityMask) = IdentityMask then
  12435. begin
  12436. DebugMsg(SPeepholeOptimization + 'Removed AND instruction since previous SHR makes this an identity operation (ShrAnd2Shr)', hp1);
  12437. { All the possible 1 bits are covered, so we can remove the AND }
  12438. hp2 := tai(hp1.Previous);
  12439. RemoveInstruction(hp1);
  12440. { p wasn't actually changed, so don't set Result to True,
  12441. but a change was nonetheless made elsewhere }
  12442. Include(OptsToCheck, aoc_ForceNewIteration);
  12443. { Do another pass in case other AND or MOVZX instructions
  12444. follow }
  12445. hp1 := hp2;
  12446. Continue;
  12447. end;
  12448. end;
  12449. end;
  12450. A_TEST, A_CMP, A_Jcc:
  12451. { Skip over conditional jumps and relevant comparisons }
  12452. Continue;
  12453. A_MOVZX:
  12454. if MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12455. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[1]^.reg) then
  12456. begin
  12457. { Since the original register is being read as is, subsequent
  12458. SHRs must not be merged at this point }
  12459. DoNotMerge := True;
  12460. if IsShrMovZFoldable(taicpu(p).opsize, taicpu(hp1).opsize, Shift) then
  12461. begin
  12462. if SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  12463. begin
  12464. DebugMsg(SPeepholeOptimization + 'Removed MOVZX instruction since previous SHR makes it unnecessary (ShrMovz2Shr)', hp1);
  12465. { All the possible 1 bits are covered, so we can remove the AND }
  12466. hp2 := tai(hp1.Previous);
  12467. RemoveInstruction(hp1);
  12468. hp1 := hp2;
  12469. end
  12470. else { Different register target }
  12471. begin
  12472. DebugMsg(SPeepholeOptimization + 'Converted MOVZX instruction to MOV since previous SHR makes zero-extension unnecessary (ShrMovz2ShrMov 2)', hp1);
  12473. taicpu(hp1).opcode := A_MOV;
  12474. setsubreg(taicpu(hp1).oper[0]^.reg, getsubreg(taicpu(hp1).oper[1]^.reg));
  12475. case taicpu(hp1).opsize of
  12476. S_BW:
  12477. taicpu(hp1).opsize := S_W;
  12478. S_BL, S_WL:
  12479. taicpu(hp1).opsize := S_L;
  12480. else
  12481. InternalError(2022081503);
  12482. end;
  12483. end;
  12484. end
  12485. else if (Shift > 0) and
  12486. (taicpu(p).opsize = S_W) and
  12487. (taicpu(hp1).opsize = S_WL) and
  12488. (taicpu(hp1).oper[0]^.reg = NR_AX) and
  12489. (taicpu(hp1).oper[1]^.reg = NR_EAX) then
  12490. begin
  12491. { Detect:
  12492. shr x, %ax (x > 0)
  12493. ...
  12494. movzwl %ax,%eax
  12495. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  12496. }
  12497. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  12498. taicpu(hp1).opcode := A_CWDE;
  12499. taicpu(hp1).clearop(0);
  12500. taicpu(hp1).clearop(1);
  12501. taicpu(hp1).ops := 0;
  12502. end;
  12503. { Move onto the next instruction }
  12504. Continue;
  12505. end;
  12506. A_SHL, A_SAL, A_SHR:
  12507. if (taicpu(hp1).opsize <= LimitSize) and
  12508. MatchOpType(taicpu(hp1), top_const, top_reg) and
  12509. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  12510. begin
  12511. { Make sure the sizes don't exceed the register size limit
  12512. (measured by the shift value falling below the limit) }
  12513. if taicpu(hp1).opsize < LimitSize then
  12514. LimitSize := taicpu(hp1).opsize;
  12515. if taicpu(hp1).opcode = A_SHR then
  12516. Inc(Shift, taicpu(hp1).oper[0]^.val)
  12517. else
  12518. begin
  12519. Dec(Shift, taicpu(hp1).oper[0]^.val);
  12520. DoNotMerge := True;
  12521. end;
  12522. if Shift < topsize2memsize[taicpu(p).opsize] - topsize2memsize[LimitSize] then
  12523. Break;
  12524. { Since we've established that the combined shift is within
  12525. limits, we can actually combine the adjacent SHR
  12526. instructions even if they're different sizes }
  12527. if not DoNotMerge and (taicpu(hp1).opcode = A_SHR) then
  12528. begin
  12529. hp2 := tai(hp1.Previous);
  12530. DebugMsg(SPeepholeOptimization + 'ShrShr2Shr 2', p);
  12531. Inc(taicpu(p).oper[0]^.val, taicpu(hp1).oper[0]^.val);
  12532. RemoveInstruction(hp1);
  12533. hp1 := hp2;
  12534. end;
  12535. { Move onto the next instruction }
  12536. Continue;
  12537. end;
  12538. else
  12539. ;
  12540. end;
  12541. Break;
  12542. until False;
  12543. { Detect the following (looking backwards):
  12544. shr %cl,%reg
  12545. shr x, %reg
  12546. Swap the two SHR instructions to minimise a pipeline stall.
  12547. }
  12548. if GetLastInstruction(p, hp1) and
  12549. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  12550. MatchOpType(taicpu(hp1), top_reg, top_reg) and
  12551. { First operand will be %cl }
  12552. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  12553. { Just to be sure }
  12554. (getsupreg(taicpu(hp1).oper[1]^.reg) <> RS_ECX) then
  12555. begin
  12556. DebugMsg(SPeepholeOptimization + 'Swapped variable and constant SHR instructions to minimise pipeline stall (ShrShr2ShrShr)', hp1);
  12557. { Moving the entries this way ensures the register tracking remains correct }
  12558. Asml.Remove(p);
  12559. Asml.InsertBefore(p, hp1);
  12560. p := hp1;
  12561. { Don't set Result to True because the current instruction is now
  12562. "shr %cl,%reg" and there's nothing more we can do with it }
  12563. end;
  12564. end;
  12565. function TX86AsmOptimizer.PostPeepholeOptADDSUB(var p : tai) : boolean;
  12566. var
  12567. hp1, hp2: tai;
  12568. Opposite, SecondOpposite: TAsmOp;
  12569. NewCond: TAsmCond;
  12570. begin
  12571. Result := False;
  12572. { Change:
  12573. add/sub 128,(dest)
  12574. To:
  12575. sub/add -128,(dest)
  12576. This generaally takes fewer bytes to encode because -128 can be stored
  12577. in a signed byte, whereas +128 cannot.
  12578. }
  12579. if (taicpu(p).opsize <> S_B) and MatchOperand(taicpu(p).oper[0]^, 128) then
  12580. begin
  12581. if taicpu(p).opcode = A_ADD then
  12582. Opposite := A_SUB
  12583. else
  12584. Opposite := A_ADD;
  12585. { Be careful if the flags are in use, because the CF flag inverts
  12586. when changing from ADD to SUB and vice versa }
  12587. if RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  12588. GetNextInstruction(p, hp1) then
  12589. begin
  12590. TransferUsedRegs(TmpUsedRegs);
  12591. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(p.Next), True);
  12592. hp2 := hp1;
  12593. { Scan ahead to check if everything's safe }
  12594. while Assigned(hp1) and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) do
  12595. begin
  12596. if (hp1.typ <> ait_instruction) then
  12597. { Probably unsafe since the flags are still in use }
  12598. Exit;
  12599. if MatchInstruction(hp1, A_CALL, A_JMP, A_RET, []) then
  12600. { Stop searching at an unconditional jump }
  12601. Break;
  12602. if not
  12603. (
  12604. MatchInstruction(hp1, A_ADC, A_SBB, []) and
  12605. (taicpu(hp1).oper[0]^.typ = top_const) { We need to be able to invert a constant }
  12606. ) and
  12607. (taicpu(hp1).condition = C_None) and RegInInstruction(NR_DEFAULTFLAGS, hp1) then
  12608. { Instruction depends on FLAGS (and is not ADC or SBB); break out }
  12609. Exit;
  12610. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  12611. TmpUsedRegs[R_SPECIALREGISTER].Update(tai(hp1.Next), True);
  12612. { Move to the next instruction }
  12613. GetNextInstruction(hp1, hp1);
  12614. end;
  12615. while Assigned(hp2) and (hp2 <> hp1) do
  12616. begin
  12617. NewCond := C_None;
  12618. case taicpu(hp2).condition of
  12619. C_A, C_NBE:
  12620. NewCond := C_BE;
  12621. C_B, C_C, C_NAE:
  12622. NewCond := C_AE;
  12623. C_AE, C_NB, C_NC:
  12624. NewCond := C_B;
  12625. C_BE, C_NA:
  12626. NewCond := C_A;
  12627. else
  12628. { No change needed };
  12629. end;
  12630. if NewCond <> C_None then
  12631. begin
  12632. DebugMsg(SPeepholeOptimization + 'Condition changed from ' + cond2str[taicpu(hp2).condition] + ' to ' + cond2str[NewCond] +
  12633. ' to accommodate ' + debug_op2str(taicpu(p).opcode) + ' -> ' + debug_op2str(opposite) + ' above', hp2);
  12634. taicpu(hp2).condition := NewCond;
  12635. end
  12636. else
  12637. if MatchInstruction(hp2, A_ADC, A_SBB, []) then
  12638. begin
  12639. { Because of the flipping of the carry bit, to ensure
  12640. the operation remains equivalent, ADC becomes SBB
  12641. and vice versa, and the constant is not-inverted.
  12642. If multiple ADCs or SBBs appear in a row, each one
  12643. changed causes the carry bit to invert, so they all
  12644. need to be flipped }
  12645. if taicpu(hp2).opcode = A_ADC then
  12646. SecondOpposite := A_SBB
  12647. else
  12648. SecondOpposite := A_ADC;
  12649. if taicpu(hp2).oper[0]^.typ <> top_const then
  12650. { Should have broken out of this optimisation already }
  12651. InternalError(2021112901);
  12652. 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]^) + ' -> ' +
  12653. 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);
  12654. { Bit-invert the constant (effectively equivalent to "-1 - val") }
  12655. taicpu(hp2).opcode := SecondOpposite;
  12656. taicpu(hp2).oper[0]^.val := not taicpu(hp2).oper[0]^.val;
  12657. end;
  12658. { Move to the next instruction }
  12659. GetNextInstruction(hp2, hp2);
  12660. end;
  12661. if (hp2 <> hp1) then
  12662. InternalError(2021111501);
  12663. end;
  12664. DebugMsg(SPeepholeOptimization + debug_op2str(taicpu(p).opcode) + debug_opsize2str(taicpu(p).opsize) + ' $128,' + debug_operstr(taicpu(p).oper[1]^) + ' changed to ' +
  12665. debug_op2str(opposite) + debug_opsize2str(taicpu(p).opsize) + ' $-128,' + debug_operstr(taicpu(p).oper[1]^) + ' to reduce instruction size', p);
  12666. taicpu(p).opcode := Opposite;
  12667. taicpu(p).oper[0]^.val := -128;
  12668. { No further optimisations can be made on this instruction, so move
  12669. onto the next one to save time }
  12670. p := tai(p.Next);
  12671. UpdateUsedRegs(p);
  12672. Result := True;
  12673. Exit;
  12674. end;
  12675. { Detect:
  12676. add/sub %reg2,(dest)
  12677. add/sub x, (dest)
  12678. (dest can be a register or a reference)
  12679. Swap the instructions to minimise a pipeline stall. This reverses the
  12680. "Add swap" and "Sub swap" optimisations done in pass 1 if no new
  12681. optimisations could be made.
  12682. }
  12683. if (taicpu(p).oper[0]^.typ = top_reg) and
  12684. not RegInOp(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^) and
  12685. (
  12686. (
  12687. (taicpu(p).oper[1]^.typ = top_reg) and
  12688. { We can try searching further ahead if we're writing to a register }
  12689. GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg)
  12690. ) or
  12691. (
  12692. (taicpu(p).oper[1]^.typ = top_ref) and
  12693. GetNextInstruction(p, hp1)
  12694. )
  12695. ) and
  12696. MatchInstruction(hp1, A_ADD, A_SUB, [taicpu(p).opsize]) and
  12697. (taicpu(hp1).oper[0]^.typ = top_const) and
  12698. MatchOperand(taicpu(p).oper[1]^, taicpu(hp1).oper[1]^) then
  12699. begin
  12700. { Make doubly sure the flags aren't in use because the order of additions may affect them }
  12701. TransferUsedRegs(TmpUsedRegs);
  12702. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  12703. hp2 := p;
  12704. while not (cs_opt_level3 in current_settings.optimizerswitches) and
  12705. GetNextInstruction(hp2, hp2) and (hp2 <> hp1) do
  12706. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  12707. if not RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  12708. begin
  12709. asml.remove(hp1);
  12710. asml.InsertBefore(hp1, p);
  12711. DebugMsg(SPeepholeOptimization + 'Add/Sub swap 2 done', hp1);
  12712. Result := True;
  12713. end;
  12714. end;
  12715. end;
  12716. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  12717. begin
  12718. Result:=false;
  12719. { change "cmp $0, %reg" to "test %reg, %reg" }
  12720. if MatchOpType(taicpu(p),top_const,top_reg) and
  12721. (taicpu(p).oper[0]^.val = 0) then
  12722. begin
  12723. taicpu(p).opcode := A_TEST;
  12724. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  12725. DebugMsg(SPeepholeOptimization + 'Cmp2Test', p);
  12726. Result:=true;
  12727. end;
  12728. end;
  12729. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  12730. var
  12731. IsTestConstX : Boolean;
  12732. hp1,hp2 : tai;
  12733. begin
  12734. Result:=false;
  12735. { removes the line marked with (x) from the sequence
  12736. and/or/xor/add/sub/... $x, %y
  12737. test/or %y, %y | test $-1, %y (x)
  12738. j(n)z _Label
  12739. as the first instruction already adjusts the ZF
  12740. %y operand may also be a reference }
  12741. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  12742. MatchOperand(taicpu(p).oper[0]^,-1);
  12743. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  12744. GetLastInstruction(p, hp1) and
  12745. (tai(hp1).typ = ait_instruction) and
  12746. GetNextInstruction(p,hp2) and
  12747. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  12748. case taicpu(hp1).opcode Of
  12749. A_ADD, A_SUB, A_OR, A_XOR, A_AND,
  12750. { These two instructions set the zero flag if the result is zero }
  12751. A_POPCNT, A_LZCNT:
  12752. begin
  12753. if (
  12754. { With POPCNT, an input of zero will set the zero flag
  12755. because the population count of zero is zero }
  12756. (taicpu(hp1).opcode = A_POPCNT) and
  12757. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) and
  12758. (
  12759. OpsEqual(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^) or
  12760. { Faster than going through the second half of the 'or'
  12761. condition below }
  12762. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^)
  12763. )
  12764. ) or (
  12765. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) and
  12766. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  12767. { and in case of carry for A(E)/B(E)/C/NC }
  12768. (
  12769. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  12770. (
  12771. (taicpu(hp1).opcode <> A_ADD) and
  12772. (taicpu(hp1).opcode <> A_SUB) and
  12773. (taicpu(hp1).opcode <> A_LZCNT)
  12774. )
  12775. )
  12776. ) then
  12777. begin
  12778. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (2-op) done', hp1);
  12779. RemoveCurrentP(p, hp2);
  12780. Result:=true;
  12781. Exit;
  12782. end;
  12783. end;
  12784. A_SHL, A_SAL, A_SHR, A_SAR:
  12785. begin
  12786. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  12787. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  12788. { therefore, it's only safe to do this optimization for }
  12789. { shifts by a (nonzero) constant }
  12790. (taicpu(hp1).oper[0]^.typ = top_const) and
  12791. (taicpu(hp1).oper[0]^.val <> 0) and
  12792. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  12793. { and in case of carry for A(E)/B(E)/C/NC }
  12794. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  12795. begin
  12796. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (shift) done', hp1);
  12797. RemoveCurrentP(p, hp2);
  12798. Result:=true;
  12799. Exit;
  12800. end;
  12801. end;
  12802. A_DEC, A_INC, A_NEG:
  12803. begin
  12804. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  12805. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  12806. { and in case of carry for A(E)/B(E)/C/NC }
  12807. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  12808. begin
  12809. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (1-op) done', hp1);
  12810. RemoveCurrentP(p, hp2);
  12811. Result:=true;
  12812. Exit;
  12813. end;
  12814. end;
  12815. A_ANDN, A_BZHI:
  12816. begin
  12817. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  12818. { Only the zero and sign flags are consistent with what the result is }
  12819. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE,C_S,C_NS]) then
  12820. begin
  12821. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (ANDN/BZHI) done', hp1);
  12822. RemoveCurrentP(p, hp2);
  12823. Result:=true;
  12824. Exit;
  12825. end;
  12826. end;
  12827. A_BEXTR:
  12828. begin
  12829. if OpsEqual(taicpu(hp1).oper[2]^,taicpu(p).oper[1]^) and
  12830. { Only the zero flag is set }
  12831. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  12832. begin
  12833. DebugMsg(SPeepholeOptimization + 'OpTest/Or2Op (BEXTR) done', hp1);
  12834. RemoveCurrentP(p, hp2);
  12835. Result:=true;
  12836. Exit;
  12837. end;
  12838. end;
  12839. else
  12840. ;
  12841. end; { case }
  12842. { change "test $-1,%reg" into "test %reg,%reg" }
  12843. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  12844. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  12845. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  12846. if MatchInstruction(p, A_OR, []) and
  12847. { Can only match if they're both registers }
  12848. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  12849. begin
  12850. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  12851. taicpu(p).opcode := A_TEST;
  12852. { No need to set Result to True, as we've done all the optimisations we can }
  12853. end;
  12854. end;
  12855. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  12856. var
  12857. hp1,hp3 : tai;
  12858. {$ifndef x86_64}
  12859. hp2 : taicpu;
  12860. {$endif x86_64}
  12861. begin
  12862. Result:=false;
  12863. hp3:=nil;
  12864. {$ifndef x86_64}
  12865. { don't do this on modern CPUs, this really hurts them due to
  12866. broken call/ret pairing }
  12867. if (current_settings.optimizecputype < cpu_Pentium2) and
  12868. not(cs_create_pic in current_settings.moduleswitches) and
  12869. GetNextInstruction(p, hp1) and
  12870. MatchInstruction(hp1,A_JMP,[S_NO]) and
  12871. MatchOpType(taicpu(hp1),top_ref) and
  12872. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  12873. begin
  12874. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  12875. taicpu(hp2).fileinfo := taicpu(p).fileinfo;
  12876. InsertLLItem(p.previous, p, hp2);
  12877. taicpu(p).opcode := A_JMP;
  12878. taicpu(p).is_jmp := true;
  12879. RemoveInstruction(hp1);
  12880. Result:=true;
  12881. end
  12882. else
  12883. {$endif x86_64}
  12884. { replace
  12885. call procname
  12886. ret
  12887. by
  12888. jmp procname
  12889. but do it only on level 4 because it destroys stack back traces
  12890. else if the subroutine is marked as no return, remove the ret
  12891. }
  12892. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  12893. (po_noreturn in current_procinfo.procdef.procoptions)) and
  12894. GetNextInstruction(p, hp1) and
  12895. (MatchInstruction(hp1,A_RET,[S_NO]) or
  12896. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  12897. SetAndTest(hp1,hp3) and
  12898. GetNextInstruction(hp1,hp1) and
  12899. MatchInstruction(hp1,A_RET,[S_NO])
  12900. )
  12901. ) and
  12902. (taicpu(hp1).ops=0) then
  12903. begin
  12904. if (cs_opt_level4 in current_settings.optimizerswitches) and
  12905. { we might destroy stack alignment here if we do not do a call }
  12906. (target_info.stackalign<=sizeof(SizeUInt)) then
  12907. begin
  12908. taicpu(p).opcode := A_JMP;
  12909. taicpu(p).is_jmp := true;
  12910. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  12911. end
  12912. else
  12913. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  12914. RemoveInstruction(hp1);
  12915. if Assigned(hp3) then
  12916. begin
  12917. AsmL.Remove(hp3);
  12918. AsmL.InsertBefore(hp3,p)
  12919. end;
  12920. Result:=true;
  12921. end;
  12922. end;
  12923. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  12924. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  12925. begin
  12926. case OpSize of
  12927. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  12928. Result := (Val <= $FF) and (Val >= -128);
  12929. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  12930. Result := (Val <= $FFFF) and (Val >= -32768);
  12931. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  12932. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  12933. else
  12934. Result := True;
  12935. end;
  12936. end;
  12937. var
  12938. hp1, hp2 : tai;
  12939. SizeChange: Boolean;
  12940. PreMessage: string;
  12941. begin
  12942. Result := False;
  12943. if (taicpu(p).oper[0]^.typ = top_reg) and
  12944. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  12945. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  12946. begin
  12947. { Change (using movzbl %al,%eax as an example):
  12948. movzbl %al, %eax movzbl %al, %eax
  12949. cmpl x, %eax testl %eax,%eax
  12950. To:
  12951. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  12952. movzbl %al, %eax movzbl %al, %eax
  12953. Smaller instruction and minimises pipeline stall as the CPU
  12954. doesn't have to wait for the register to get zero-extended. [Kit]
  12955. Also allow if the smaller of the two registers is being checked,
  12956. as this still removes the false dependency.
  12957. }
  12958. if
  12959. (
  12960. (
  12961. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  12962. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  12963. ) or (
  12964. { If MatchOperand returns True, they must both be registers }
  12965. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  12966. )
  12967. ) and
  12968. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  12969. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  12970. begin
  12971. 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);
  12972. asml.Remove(hp1);
  12973. asml.InsertBefore(hp1, p);
  12974. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  12975. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  12976. begin
  12977. taicpu(hp1).opcode := A_TEST;
  12978. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  12979. end;
  12980. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  12981. case taicpu(p).opsize of
  12982. S_BW, S_BL:
  12983. begin
  12984. SizeChange := taicpu(hp1).opsize <> S_B;
  12985. taicpu(hp1).changeopsize(S_B);
  12986. end;
  12987. S_WL:
  12988. begin
  12989. SizeChange := taicpu(hp1).opsize <> S_W;
  12990. taicpu(hp1).changeopsize(S_W);
  12991. end
  12992. else
  12993. InternalError(2020112701);
  12994. end;
  12995. UpdateUsedRegs(tai(p.Next));
  12996. { Check if the register is used aferwards - if not, we can
  12997. remove the movzx instruction completely }
  12998. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  12999. begin
  13000. { Hp1 is a better position than p for debugging purposes }
  13001. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  13002. RemoveCurrentp(p, hp1);
  13003. Result := True;
  13004. end;
  13005. if SizeChange then
  13006. DebugMsg(SPeepholeOptimization + PreMessage +
  13007. 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)
  13008. else
  13009. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  13010. Exit;
  13011. end;
  13012. { Change (using movzwl %ax,%eax as an example):
  13013. movzwl %ax, %eax
  13014. movb %al, (dest) (Register is smaller than read register in movz)
  13015. To:
  13016. movb %al, (dest) (Move one back to avoid a false dependency)
  13017. movzwl %ax, %eax
  13018. }
  13019. if (taicpu(hp1).opcode = A_MOV) and
  13020. (taicpu(hp1).oper[0]^.typ = top_reg) and
  13021. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  13022. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  13023. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  13024. begin
  13025. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  13026. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  13027. asml.Remove(hp1);
  13028. asml.InsertBefore(hp1, p);
  13029. if taicpu(hp1).oper[1]^.typ = top_reg then
  13030. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  13031. { Check if the register is used aferwards - if not, we can
  13032. remove the movzx instruction completely }
  13033. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  13034. begin
  13035. { Hp1 is a better position than p for debugging purposes }
  13036. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  13037. RemoveCurrentp(p, hp1);
  13038. Result := True;
  13039. end;
  13040. Exit;
  13041. end;
  13042. end;
  13043. end;
  13044. {$ifdef x86_64}
  13045. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  13046. var
  13047. PreMessage, RegName: string;
  13048. begin
  13049. { Code size reduction by J. Gareth "Kit" Moreton }
  13050. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  13051. as this removes the REX prefix }
  13052. Result := False;
  13053. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  13054. Exit;
  13055. if taicpu(p).oper[0]^.typ <> top_reg then
  13056. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  13057. InternalError(2018011500);
  13058. case taicpu(p).opsize of
  13059. S_Q:
  13060. begin
  13061. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  13062. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  13063. { The actual optimization }
  13064. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  13065. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  13066. taicpu(p).changeopsize(S_L);
  13067. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  13068. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (32-bit register recommended when zeroing 64-bit counterpart)', p);
  13069. end;
  13070. else
  13071. ;
  13072. end;
  13073. end;
  13074. {$endif}
  13075. function TX86AsmOptimizer.PostPeepholeOptVPXOR(var p : tai) : Boolean;
  13076. var
  13077. XReg: TRegister;
  13078. begin
  13079. Result := False;
  13080. { Turn "vpxor %ymmreg2,%ymmreg2,%ymmreg1" to "vpxor %xmmreg2,%xmmreg2,%xmmreg1"
  13081. Smaller encoding and slightly faster on some platforms (also works for
  13082. ZMM-sized registers) }
  13083. if (taicpu(p).opsize in [S_YMM, S_ZMM]) and
  13084. MatchOpType(taicpu(p), top_reg, top_reg, top_reg) then
  13085. begin
  13086. XReg := taicpu(p).oper[0]^.reg;
  13087. if (taicpu(p).oper[1]^.reg = XReg) then
  13088. begin
  13089. taicpu(p).changeopsize(S_XMM);
  13090. setsubreg(taicpu(p).oper[2]^.reg, R_SUBMMX);
  13091. if (cs_opt_size in current_settings.optimizerswitches) then
  13092. begin
  13093. { Change input registers to %xmm0 to reduce size. Note that
  13094. there's a risk of a false dependency doing this, so only
  13095. optimise for size here }
  13096. XReg := NR_XMM0;
  13097. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM and changed input registers to %xmm0 to reduce size', p);
  13098. end
  13099. else
  13100. begin
  13101. setsubreg(XReg, R_SUBMMX);
  13102. DebugMsg(SPeepholeOptimization + 'Changed zero-setting vpxor from Y/ZMM to XMM to reduce size and increase efficiency', p);
  13103. end;
  13104. taicpu(p).oper[0]^.reg := XReg;
  13105. taicpu(p).oper[1]^.reg := XReg;
  13106. Result := True;
  13107. end;
  13108. end;
  13109. end;
  13110. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  13111. var
  13112. OperIdx: Integer;
  13113. begin
  13114. for OperIdx := 0 to p.ops - 1 do
  13115. if p.oper[OperIdx]^.typ = top_ref then
  13116. optimize_ref(p.oper[OperIdx]^.ref^, False);
  13117. end;
  13118. end.