aoptx86.pas 426 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995
  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. interface
  21. uses
  22. globtype,
  23. cpubase,
  24. aasmtai,aasmcpu,
  25. cgbase,cgutils,
  26. aopt,aoptobj;
  27. type
  28. TOptsToCheck = (
  29. aoc_MovAnd2Mov_3
  30. );
  31. TX86AsmOptimizer = class(TAsmOptimizer)
  32. { some optimizations are very expensive to check, so the
  33. pre opt pass can be used to set some flags, depending on the found
  34. instructions if it is worth to check a certain optimization }
  35. OptsToCheck : set of TOptsToCheck;
  36. function RegLoadedWithNewValue(reg : tregister; hp : tai) : boolean; override;
  37. function InstructionLoadsFromReg(const reg : TRegister; const hp : tai) : boolean; override;
  38. function RegReadByInstruction(reg : TRegister; hp : tai) : boolean;
  39. function RegInInstruction(Reg: TRegister; p1: tai): Boolean;override;
  40. function GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  41. { This version of GetNextInstructionUsingReg will look across conditional jumps,
  42. potentially allowing further optimisation (although it might need to know if
  43. it crossed a conditional jump. }
  44. function GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  45. {
  46. In comparison with GetNextInstructionUsingReg, GetNextInstructionUsingRegTrackingUse tracks
  47. the use of a register by allocs/dealloc, so it can ignore calls.
  48. In the following example, GetNextInstructionUsingReg will return the second movq,
  49. GetNextInstructionUsingRegTrackingUse won't.
  50. movq %rdi,%rax
  51. # Register rdi released
  52. # Register rdi allocated
  53. movq %rax,%rdi
  54. While in this example:
  55. movq %rdi,%rax
  56. call proc
  57. movq %rdi,%rax
  58. GetNextInstructionUsingRegTrackingUse will return the second instruction while GetNextInstructionUsingReg
  59. won't.
  60. }
  61. function GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  62. function RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean; override;
  63. private
  64. function SkipSimpleInstructions(var hp1: tai): Boolean;
  65. protected
  66. class function IsMOVZXAcceptable: Boolean; static; inline;
  67. { checks whether loading a new value in reg1 overwrites the entirety of reg2 }
  68. function Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  69. { checks whether reading the value in reg1 depends on the value of reg2. This
  70. is very similar to SuperRegisterEquals, except it takes into account that
  71. R_SUBH and R_SUBL are independendent (e.g. reading from AL does not
  72. depend on the value in AH). }
  73. function Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  74. { Replaces all references to AOldReg in a memory reference to ANewReg }
  75. class function ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean; static;
  76. { Replaces all references to AOldReg in an operand to ANewReg }
  77. class function ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean; static;
  78. { Replaces all references to AOldReg in an instruction to ANewReg,
  79. except where the register is being written }
  80. function ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  81. { Returns true if the reference only refers to ESP or EBP (or their 64-bit equivalents),
  82. or writes to a global symbol }
  83. class function IsRefSafe(const ref: PReference): Boolean; static; inline;
  84. { Returns true if the given MOV instruction can be safely converted to CMOV }
  85. class function CanBeCMOV(p : tai) : boolean; static;
  86. { Converts the LEA instruction to ADD/INC/SUB/DEC. Returns True if the
  87. conversion was successful }
  88. function ConvertLEA(const p : taicpu): Boolean;
  89. function DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  90. procedure DebugMsg(const s : string; p : tai);inline;
  91. class function IsExitCode(p : tai) : boolean; static;
  92. class function isFoldableArithOp(hp1 : taicpu; reg : tregister) : boolean; static;
  93. procedure RemoveLastDeallocForFuncRes(p : tai);
  94. function DoSubAddOpt(var p : tai) : Boolean;
  95. function PrePeepholeOptSxx(var p : tai) : boolean;
  96. function PrePeepholeOptIMUL(var p : tai) : boolean;
  97. function PrePeepholeOptAND(var p : tai) : boolean;
  98. function OptPass1Test(var p: tai): boolean;
  99. function OptPass1Add(var p: tai): boolean;
  100. function OptPass1AND(var p : tai) : boolean;
  101. function OptPass1_V_MOVAP(var p : tai) : boolean;
  102. function OptPass1VOP(var p : tai) : boolean;
  103. function OptPass1MOV(var p : tai) : boolean;
  104. function OptPass1Movx(var p : tai) : boolean;
  105. function OptPass1MOVXX(var p : tai) : boolean;
  106. function OptPass1OP(var p : tai) : boolean;
  107. function OptPass1LEA(var p : tai) : boolean;
  108. function OptPass1Sub(var p : tai) : boolean;
  109. function OptPass1SHLSAL(var p : tai) : boolean;
  110. function OptPass1FSTP(var p : tai) : boolean;
  111. function OptPass1FLD(var p : tai) : boolean;
  112. function OptPass1Cmp(var p : tai) : boolean;
  113. function OptPass1PXor(var p : tai) : boolean;
  114. function OptPass1VPXor(var p: tai): boolean;
  115. function OptPass1Imul(var p : tai) : boolean;
  116. function OptPass1Jcc(var p : tai) : boolean;
  117. function OptPass1SHXX(var p: tai): boolean;
  118. function OptPass2Movx(var p : tai): Boolean;
  119. function OptPass2MOV(var p : tai) : boolean;
  120. function OptPass2Imul(var p : tai) : boolean;
  121. function OptPass2Jmp(var p : tai) : boolean;
  122. function OptPass2Jcc(var p : tai) : boolean;
  123. function OptPass2Lea(var p: tai): Boolean;
  124. function OptPass2SUB(var p: tai): Boolean;
  125. function OptPass2ADD(var p : tai): Boolean;
  126. function OptPass2SETcc(var p : tai) : boolean;
  127. function CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  128. function PostPeepholeOptMov(var p : tai) : Boolean;
  129. function PostPeepholeOptMovzx(var p : tai) : Boolean;
  130. {$ifdef x86_64} { These post-peephole optimisations only affect 64-bit registers. [Kit] }
  131. function PostPeepholeOptXor(var p : tai) : Boolean;
  132. {$endif}
  133. function PostPeepholeOptAnd(var p : tai) : boolean;
  134. function PostPeepholeOptMOVSX(var p : tai) : boolean;
  135. function PostPeepholeOptCmp(var p : tai) : Boolean;
  136. function PostPeepholeOptTestOr(var p : tai) : Boolean;
  137. function PostPeepholeOptCall(var p : tai) : Boolean;
  138. function PostPeepholeOptLea(var p : tai) : Boolean;
  139. function PostPeepholeOptPush(var p: tai): Boolean;
  140. function PostPeepholeOptShr(var p : tai) : boolean;
  141. procedure ConvertJumpToRET(const p: tai; const ret_p: tai);
  142. function CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  143. procedure SwapMovCmp(var p, hp1: tai);
  144. { Processor-dependent reference optimisation }
  145. class procedure OptimizeRefs(var p: taicpu); static;
  146. end;
  147. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  148. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  149. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  150. function MatchInstruction(const instr: tai; const ops: array of TAsmOp; const opsize: topsizes): boolean;
  151. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  152. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  153. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  154. {$if max_operands>2}
  155. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  156. {$endif max_operands>2}
  157. function RefsEqual(const r1, r2: treference): boolean;
  158. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  159. { returns true, if ref is a reference using only the registers passed as base and index
  160. and having an offset }
  161. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  162. implementation
  163. uses
  164. cutils,verbose,
  165. systems,
  166. globals,
  167. cpuinfo,
  168. procinfo,
  169. paramgr,
  170. aasmbase,
  171. aoptbase,aoptutils,
  172. symconst,symsym,
  173. cgx86,
  174. itcpugas;
  175. {$ifdef DEBUG_AOPTCPU}
  176. const
  177. SPeepholeOptimization: shortstring = 'Peephole Optimization: ';
  178. {$else DEBUG_AOPTCPU}
  179. { Empty strings help the optimizer to remove string concatenations that won't
  180. ever appear to the user on release builds. [Kit] }
  181. const
  182. SPeepholeOptimization = '';
  183. {$endif DEBUG_AOPTCPU}
  184. LIST_STEP_SIZE = 4;
  185. function MatchInstruction(const instr: tai; const op: TAsmOp; const opsize: topsizes): boolean;
  186. begin
  187. result :=
  188. (instr.typ = ait_instruction) and
  189. (taicpu(instr).opcode = op) and
  190. ((opsize = []) or (taicpu(instr).opsize in opsize));
  191. end;
  192. function MatchInstruction(const instr: tai; const op1,op2: TAsmOp; const opsize: topsizes): boolean;
  193. begin
  194. result :=
  195. (instr.typ = ait_instruction) and
  196. ((taicpu(instr).opcode = op1) or
  197. (taicpu(instr).opcode = op2)
  198. ) and
  199. ((opsize = []) or (taicpu(instr).opsize in opsize));
  200. end;
  201. function MatchInstruction(const instr: tai; const op1,op2,op3: TAsmOp; const opsize: topsizes): boolean;
  202. begin
  203. result :=
  204. (instr.typ = ait_instruction) and
  205. ((taicpu(instr).opcode = op1) or
  206. (taicpu(instr).opcode = op2) or
  207. (taicpu(instr).opcode = op3)
  208. ) and
  209. ((opsize = []) or (taicpu(instr).opsize in opsize));
  210. end;
  211. function MatchInstruction(const instr : tai;const ops : array of TAsmOp;
  212. const opsize : topsizes) : boolean;
  213. var
  214. op : TAsmOp;
  215. begin
  216. result:=false;
  217. for op in ops do
  218. begin
  219. if (instr.typ = ait_instruction) and
  220. (taicpu(instr).opcode = op) and
  221. ((opsize = []) or (taicpu(instr).opsize in opsize)) then
  222. begin
  223. result:=true;
  224. exit;
  225. end;
  226. end;
  227. end;
  228. function MatchOperand(const oper: TOper; const reg: TRegister): boolean; inline;
  229. begin
  230. result := (oper.typ = top_reg) and (oper.reg = reg);
  231. end;
  232. function MatchOperand(const oper: TOper; const a: tcgint): boolean; inline;
  233. begin
  234. result := (oper.typ = top_const) and (oper.val = a);
  235. end;
  236. function MatchOperand(const oper1: TOper; const oper2: TOper): boolean;
  237. begin
  238. result := oper1.typ = oper2.typ;
  239. if result then
  240. case oper1.typ of
  241. top_const:
  242. Result:=oper1.val = oper2.val;
  243. top_reg:
  244. Result:=oper1.reg = oper2.reg;
  245. top_ref:
  246. Result:=RefsEqual(oper1.ref^, oper2.ref^);
  247. else
  248. internalerror(2013102801);
  249. end
  250. end;
  251. function MatchOperand(const oper1: TOper; const oper2: TOper; const oper3: TOper): boolean;
  252. begin
  253. result := (oper1.typ = oper2.typ) and (oper1.typ = oper3.typ);
  254. if result then
  255. case oper1.typ of
  256. top_const:
  257. Result:=(oper1.val = oper2.val) and (oper1.val = oper3.val);
  258. top_reg:
  259. Result:=(oper1.reg = oper2.reg) and (oper1.reg = oper3.reg);
  260. top_ref:
  261. Result:=RefsEqual(oper1.ref^, oper2.ref^) and RefsEqual(oper1.ref^, oper3.ref^);
  262. else
  263. internalerror(2020052401);
  264. end
  265. end;
  266. function RefsEqual(const r1, r2: treference): boolean;
  267. begin
  268. RefsEqual :=
  269. (r1.offset = r2.offset) and
  270. (r1.segment = r2.segment) and (r1.base = r2.base) and
  271. (r1.index = r2.index) and (r1.scalefactor = r2.scalefactor) and
  272. (r1.symbol=r2.symbol) and (r1.refaddr = r2.refaddr) and
  273. (r1.relsymbol = r2.relsymbol) and
  274. (r1.volatility=[]) and
  275. (r2.volatility=[]);
  276. end;
  277. function MatchReference(const ref : treference;base,index : TRegister) : Boolean;
  278. begin
  279. Result:=(ref.offset=0) and
  280. (ref.scalefactor in [0,1]) and
  281. (ref.segment=NR_NO) and
  282. (ref.symbol=nil) and
  283. (ref.relsymbol=nil) and
  284. ((base=NR_INVALID) or
  285. (ref.base=base)) and
  286. ((index=NR_INVALID) or
  287. (ref.index=index)) and
  288. (ref.volatility=[]);
  289. end;
  290. function MatchReferenceWithOffset(const ref : treference;base,index : TRegister) : Boolean;
  291. begin
  292. Result:=(ref.scalefactor in [0,1]) and
  293. (ref.segment=NR_NO) and
  294. (ref.symbol=nil) and
  295. (ref.relsymbol=nil) and
  296. ((base=NR_INVALID) or
  297. (ref.base=base)) and
  298. ((index=NR_INVALID) or
  299. (ref.index=index)) and
  300. (ref.volatility=[]);
  301. end;
  302. function InstrReadsFlags(p: tai): boolean;
  303. begin
  304. InstrReadsFlags := true;
  305. case p.typ of
  306. ait_instruction:
  307. if InsProp[taicpu(p).opcode].Ch*
  308. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  309. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  310. Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc,Ch_All]<>[] then
  311. exit;
  312. ait_label:
  313. exit;
  314. else
  315. ;
  316. end;
  317. InstrReadsFlags := false;
  318. end;
  319. function TX86AsmOptimizer.GetNextInstructionUsingReg(Current: tai; out Next: tai; reg: TRegister): Boolean;
  320. begin
  321. Next:=Current;
  322. repeat
  323. Result:=GetNextInstruction(Next,Next);
  324. until not (Result) or
  325. not(cs_opt_level3 in current_settings.optimizerswitches) or
  326. (Next.typ<>ait_instruction) or
  327. RegInInstruction(reg,Next) or
  328. is_calljmp(taicpu(Next).opcode);
  329. end;
  330. function TX86AsmOptimizer.GetNextInstructionUsingRegCond(Current: tai; out Next: tai; reg: TRegister; var CrossJump: Boolean): Boolean;
  331. begin
  332. { Note, CrossJump keeps its input value if a conditional jump is not found - it doesn't get set to False }
  333. Next := Current;
  334. repeat
  335. Result := GetNextInstruction(Next,Next);
  336. if Result and (Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) then
  337. if is_calljmpuncond(taicpu(Next).opcode) then
  338. begin
  339. Result := False;
  340. Exit;
  341. end
  342. else
  343. CrossJump := True;
  344. until not Result or
  345. not (cs_opt_level3 in current_settings.optimizerswitches) or
  346. (Next.typ <> ait_instruction) or
  347. RegInInstruction(reg,Next);
  348. end;
  349. function TX86AsmOptimizer.GetNextInstructionUsingRegTrackingUse(Current: tai; out Next: tai; reg: TRegister): Boolean;
  350. begin
  351. if not(cs_opt_level3 in current_settings.optimizerswitches) then
  352. begin
  353. Result:=GetNextInstruction(Current,Next);
  354. exit;
  355. end;
  356. Next:=tai(Current.Next);
  357. Result:=false;
  358. while assigned(Next) do
  359. begin
  360. if ((Next.typ=ait_instruction) and is_calljmp(taicpu(Next).opcode) and not(taicpu(Next).opcode=A_CALL)) or
  361. ((Next.typ=ait_regalloc) and (getsupreg(tai_regalloc(Next).reg)=getsupreg(reg))) or
  362. ((Next.typ=ait_label) and not(labelCanBeSkipped(Tai_Label(Next)))) then
  363. exit
  364. else if (Next.typ=ait_instruction) and RegInInstruction(reg,Next) and not(taicpu(Next).opcode=A_CALL) then
  365. begin
  366. Result:=true;
  367. exit;
  368. end;
  369. Next:=tai(Next.Next);
  370. end;
  371. end;
  372. function TX86AsmOptimizer.InstructionLoadsFromReg(const reg: TRegister;const hp: tai): boolean;
  373. begin
  374. Result:=RegReadByInstruction(reg,hp);
  375. end;
  376. function TX86AsmOptimizer.RegReadByInstruction(reg: TRegister; hp: tai): boolean;
  377. var
  378. p: taicpu;
  379. opcount: longint;
  380. begin
  381. RegReadByInstruction := false;
  382. if hp.typ <> ait_instruction then
  383. exit;
  384. p := taicpu(hp);
  385. case p.opcode of
  386. A_CALL:
  387. regreadbyinstruction := true;
  388. A_IMUL:
  389. case p.ops of
  390. 1:
  391. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  392. (
  393. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  394. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  395. );
  396. 2,3:
  397. regReadByInstruction :=
  398. reginop(reg,p.oper[0]^) or
  399. reginop(reg,p.oper[1]^);
  400. else
  401. InternalError(2019112801);
  402. end;
  403. A_MUL:
  404. begin
  405. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  406. (
  407. ((getregtype(reg)=R_INTREGISTER) and (getsupreg(reg)=RS_EAX)) and
  408. ((getsubreg(reg)<>R_SUBH) or (p.opsize<>S_B))
  409. );
  410. end;
  411. A_IDIV,A_DIV:
  412. begin
  413. regReadByInstruction := RegInOp(reg,p.oper[0]^) or
  414. (
  415. (getregtype(reg)=R_INTREGISTER) and
  416. (
  417. (getsupreg(reg)=RS_EAX) or ((getsupreg(reg)=RS_EDX) and (p.opsize<>S_B))
  418. )
  419. );
  420. end;
  421. else
  422. begin
  423. if (p.opcode=A_LEA) and is_segment_reg(reg) then
  424. begin
  425. RegReadByInstruction := false;
  426. exit;
  427. end;
  428. for opcount := 0 to p.ops-1 do
  429. if (p.oper[opCount]^.typ = top_ref) and
  430. RegInRef(reg,p.oper[opcount]^.ref^) then
  431. begin
  432. RegReadByInstruction := true;
  433. exit
  434. end;
  435. { special handling for SSE MOVSD }
  436. if (p.opcode=A_MOVSD) and (p.ops>0) then
  437. begin
  438. if p.ops<>2 then
  439. internalerror(2017042702);
  440. regReadByInstruction := reginop(reg,p.oper[0]^) or
  441. (
  442. (p.oper[1]^.typ=top_reg) and (p.oper[0]^.typ=top_reg) and reginop(reg, p.oper[1]^)
  443. );
  444. exit;
  445. end;
  446. with insprop[p.opcode] do
  447. begin
  448. if getregtype(reg)=R_INTREGISTER then
  449. begin
  450. case getsupreg(reg) of
  451. RS_EAX:
  452. if [Ch_REAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  453. begin
  454. RegReadByInstruction := true;
  455. exit
  456. end;
  457. RS_ECX:
  458. if [Ch_RECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  459. begin
  460. RegReadByInstruction := true;
  461. exit
  462. end;
  463. RS_EDX:
  464. if [Ch_REDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  465. begin
  466. RegReadByInstruction := true;
  467. exit
  468. end;
  469. RS_EBX:
  470. if [Ch_REBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  471. begin
  472. RegReadByInstruction := true;
  473. exit
  474. end;
  475. RS_ESP:
  476. if [Ch_RESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  477. begin
  478. RegReadByInstruction := true;
  479. exit
  480. end;
  481. RS_EBP:
  482. if [Ch_REBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  483. begin
  484. RegReadByInstruction := true;
  485. exit
  486. end;
  487. RS_ESI:
  488. if [Ch_RESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  489. begin
  490. RegReadByInstruction := true;
  491. exit
  492. end;
  493. RS_EDI:
  494. if [Ch_REDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  495. begin
  496. RegReadByInstruction := true;
  497. exit
  498. end;
  499. end;
  500. end;
  501. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  502. begin
  503. if (Ch_RFLAGScc in Ch) and not(getsubreg(reg) in [R_SUBW,R_SUBD,R_SUBQ]) then
  504. begin
  505. case p.condition of
  506. C_A,C_NBE, { CF=0 and ZF=0 }
  507. C_BE,C_NA: { CF=1 or ZF=1 }
  508. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY,R_SUBFLAGZERO];
  509. C_AE,C_NB,C_NC, { CF=0 }
  510. C_B,C_NAE,C_C: { CF=1 }
  511. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGCARRY];
  512. C_NE,C_NZ, { ZF=0 }
  513. C_E,C_Z: { ZF=1 }
  514. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO];
  515. C_G,C_NLE, { ZF=0 and SF=OF }
  516. C_LE,C_NG: { ZF=1 or SF<>OF }
  517. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGZERO,R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  518. C_GE,C_NL, { SF=OF }
  519. C_L,C_NGE: { SF<>OF }
  520. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN,R_SUBFLAGOVERFLOW];
  521. C_NO, { OF=0 }
  522. C_O: { OF=1 }
  523. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGOVERFLOW];
  524. C_NP,C_PO, { PF=0 }
  525. C_P,C_PE: { PF=1 }
  526. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGPARITY];
  527. C_NS, { SF=0 }
  528. C_S: { SF=1 }
  529. RegReadByInstruction:=getsubreg(reg) in [R_SUBFLAGSIGN];
  530. else
  531. internalerror(2017042701);
  532. end;
  533. if RegReadByInstruction then
  534. exit;
  535. end;
  536. case getsubreg(reg) of
  537. R_SUBW,R_SUBD,R_SUBQ:
  538. RegReadByInstruction :=
  539. [Ch_RCarryFlag,Ch_RParityFlag,Ch_RAuxiliaryFlag,Ch_RZeroFlag,Ch_RSignFlag,Ch_ROverflowFlag,
  540. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  541. Ch_RDirFlag,Ch_RFlags,Ch_RWFlags,Ch_RFLAGScc]*Ch<>[];
  542. R_SUBFLAGCARRY:
  543. RegReadByInstruction:=[Ch_RCarryFlag,Ch_RWCarryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  544. R_SUBFLAGPARITY:
  545. RegReadByInstruction:=[Ch_RParityFlag,Ch_RWParityFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  546. R_SUBFLAGAUXILIARY:
  547. RegReadByInstruction:=[Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  548. R_SUBFLAGZERO:
  549. RegReadByInstruction:=[Ch_RZeroFlag,Ch_RWZeroFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  550. R_SUBFLAGSIGN:
  551. RegReadByInstruction:=[Ch_RSignFlag,Ch_RWSignFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  552. R_SUBFLAGOVERFLOW:
  553. RegReadByInstruction:=[Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  554. R_SUBFLAGINTERRUPT:
  555. RegReadByInstruction:=[Ch_RFlags,Ch_RWFlags]*Ch<>[];
  556. R_SUBFLAGDIRECTION:
  557. RegReadByInstruction:=[Ch_RDirFlag,Ch_RFlags,Ch_RWFlags]*Ch<>[];
  558. else
  559. internalerror(2017042601);
  560. end;
  561. exit;
  562. end;
  563. if (Ch_NoReadIfEqualRegs in Ch) and (p.ops=2) and
  564. (p.oper[0]^.typ=top_reg) and (p.oper[1]^.typ=top_reg) and
  565. (p.oper[0]^.reg=p.oper[1]^.reg) then
  566. exit;
  567. if ([CH_RWOP1,CH_ROP1,CH_MOP1]*Ch<>[]) and reginop(reg,p.oper[0]^) then
  568. begin
  569. RegReadByInstruction := true;
  570. exit
  571. end;
  572. if ([Ch_RWOP2,Ch_ROP2,Ch_MOP2]*Ch<>[]) and reginop(reg,p.oper[1]^) then
  573. begin
  574. RegReadByInstruction := true;
  575. exit
  576. end;
  577. if ([Ch_RWOP3,Ch_ROP3,Ch_MOP3]*Ch<>[]) and reginop(reg,p.oper[2]^) then
  578. begin
  579. RegReadByInstruction := true;
  580. exit
  581. end;
  582. if ([Ch_RWOP4,Ch_ROP4,Ch_MOP4]*Ch<>[]) and reginop(reg,p.oper[3]^) then
  583. begin
  584. RegReadByInstruction := true;
  585. exit
  586. end;
  587. end;
  588. end;
  589. end;
  590. end;
  591. function TX86AsmOptimizer.RegInInstruction(Reg: TRegister; p1: tai): Boolean;
  592. begin
  593. result:=false;
  594. if p1.typ<>ait_instruction then
  595. exit;
  596. if (Ch_All in insprop[taicpu(p1).opcode].Ch) then
  597. exit(true);
  598. if (getregtype(reg)=R_INTREGISTER) and
  599. { change information for xmm movsd are not correct }
  600. ((taicpu(p1).opcode<>A_MOVSD) or (taicpu(p1).ops=0)) then
  601. begin
  602. case getsupreg(reg) of
  603. { RS_EAX = RS_RAX on x86-64 }
  604. RS_EAX:
  605. result:=([Ch_REAX,Ch_RRAX,Ch_WEAX,Ch_WRAX,Ch_RWEAX,Ch_RWRAX,Ch_MEAX,Ch_MRAX]*insprop[taicpu(p1).opcode].Ch)<>[];
  606. RS_ECX:
  607. result:=([Ch_RECX,Ch_RRCX,Ch_WECX,Ch_WRCX,Ch_RWECX,Ch_RWRCX,Ch_MECX,Ch_MRCX]*insprop[taicpu(p1).opcode].Ch)<>[];
  608. RS_EDX:
  609. result:=([Ch_REDX,Ch_RRDX,Ch_WEDX,Ch_WRDX,Ch_RWEDX,Ch_RWRDX,Ch_MEDX,Ch_MRDX]*insprop[taicpu(p1).opcode].Ch)<>[];
  610. RS_EBX:
  611. result:=([Ch_REBX,Ch_RRBX,Ch_WEBX,Ch_WRBX,Ch_RWEBX,Ch_RWRBX,Ch_MEBX,Ch_MRBX]*insprop[taicpu(p1).opcode].Ch)<>[];
  612. RS_ESP:
  613. result:=([Ch_RESP,Ch_RRSP,Ch_WESP,Ch_WRSP,Ch_RWESP,Ch_RWRSP,Ch_MESP,Ch_MRSP]*insprop[taicpu(p1).opcode].Ch)<>[];
  614. RS_EBP:
  615. result:=([Ch_REBP,Ch_RRBP,Ch_WEBP,Ch_WRBP,Ch_RWEBP,Ch_RWRBP,Ch_MEBP,Ch_MRBP]*insprop[taicpu(p1).opcode].Ch)<>[];
  616. RS_ESI:
  617. result:=([Ch_RESI,Ch_RRSI,Ch_WESI,Ch_WRSI,Ch_RWESI,Ch_RWRSI,Ch_MESI,Ch_MRSI,Ch_RMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  618. RS_EDI:
  619. result:=([Ch_REDI,Ch_RRDI,Ch_WEDI,Ch_WRDI,Ch_RWEDI,Ch_RWRDI,Ch_MEDI,Ch_MRDI,Ch_WMemEDI]*insprop[taicpu(p1).opcode].Ch)<>[];
  620. else
  621. ;
  622. end;
  623. if result then
  624. exit;
  625. end
  626. else if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  627. begin
  628. if ([Ch_RFlags,Ch_WFlags,Ch_RWFlags,Ch_RFLAGScc]*insprop[taicpu(p1).opcode].Ch)<>[] then
  629. exit(true);
  630. case getsubreg(reg) of
  631. R_SUBFLAGCARRY:
  632. Result:=([Ch_RCarryFlag,Ch_RWCarryFlag,Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  633. R_SUBFLAGPARITY:
  634. Result:=([Ch_RParityFlag,Ch_RWParityFlag,Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  635. R_SUBFLAGAUXILIARY:
  636. Result:=([Ch_RAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  637. R_SUBFLAGZERO:
  638. Result:=([Ch_RZeroFlag,Ch_RWZeroFlag,Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  639. R_SUBFLAGSIGN:
  640. Result:=([Ch_RSignFlag,Ch_RWSignFlag,Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  641. R_SUBFLAGOVERFLOW:
  642. Result:=([Ch_ROverflowFlag,Ch_RWOverflowFlag,Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag]*insprop[taicpu(p1).opcode].Ch)<>[];
  643. R_SUBFLAGINTERRUPT:
  644. Result:=([Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  645. R_SUBFLAGDIRECTION:
  646. Result:=([Ch_RDirFlag,Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*insprop[taicpu(p1).opcode].Ch)<>[];
  647. else
  648. ;
  649. end;
  650. if result then
  651. exit;
  652. end
  653. else if (getregtype(reg)=R_FPUREGISTER) and (Ch_FPU in insprop[taicpu(p1).opcode].Ch) then
  654. exit(true);
  655. Result:=inherited RegInInstruction(Reg, p1);
  656. end;
  657. function TX86AsmOptimizer.RegModifiedByInstruction(Reg: TRegister; p1: tai): boolean;
  658. begin
  659. Result := False;
  660. if p1.typ <> ait_instruction then
  661. exit;
  662. with insprop[taicpu(p1).opcode] do
  663. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  664. begin
  665. case getsubreg(reg) of
  666. R_SUBW,R_SUBD,R_SUBQ:
  667. Result :=
  668. [Ch_WCarryFlag,Ch_WParityFlag,Ch_WAuxiliaryFlag,Ch_WZeroFlag,Ch_WSignFlag,Ch_WOverflowFlag,
  669. Ch_RWCarryFlag,Ch_RWParityFlag,Ch_RWAuxiliaryFlag,Ch_RWZeroFlag,Ch_RWSignFlag,Ch_RWOverflowFlag,
  670. Ch_W0DirFlag,Ch_W1DirFlag,Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  671. R_SUBFLAGCARRY:
  672. Result:=[Ch_WCarryFlag,Ch_RWCarryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  673. R_SUBFLAGPARITY:
  674. Result:=[Ch_WParityFlag,Ch_RWParityFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  675. R_SUBFLAGAUXILIARY:
  676. Result:=[Ch_WAuxiliaryFlag,Ch_RWAuxiliaryFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  677. R_SUBFLAGZERO:
  678. Result:=[Ch_WZeroFlag,Ch_RWZeroFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  679. R_SUBFLAGSIGN:
  680. Result:=[Ch_WSignFlag,Ch_RWSignFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  681. R_SUBFLAGOVERFLOW:
  682. Result:=[Ch_WOverflowFlag,Ch_RWOverflowFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  683. R_SUBFLAGINTERRUPT:
  684. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  685. R_SUBFLAGDIRECTION:
  686. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags,Ch_RWFlags]*Ch<>[];
  687. else
  688. internalerror(2017042602);
  689. end;
  690. exit;
  691. end;
  692. case taicpu(p1).opcode of
  693. A_CALL:
  694. { We could potentially set Result to False if the register in
  695. question is non-volatile for the subroutine's calling convention,
  696. but this would require detecting the calling convention in use and
  697. also assuming that the routine doesn't contain malformed assembly
  698. language, for example... so it could only be done under -O4 as it
  699. would be considered a side-effect. [Kit] }
  700. Result := True;
  701. A_MOVSD:
  702. { special handling for SSE MOVSD }
  703. if (taicpu(p1).ops>0) then
  704. begin
  705. if taicpu(p1).ops<>2 then
  706. internalerror(2017042703);
  707. Result := (taicpu(p1).oper[1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[1]^);
  708. end;
  709. { VMOVSS and VMOVSD has two and three operand flavours, this cannot modelled by x86ins.dat
  710. so fix it here (FK)
  711. }
  712. A_VMOVSS,
  713. A_VMOVSD:
  714. begin
  715. Result := (taicpu(p1).ops=3) and (taicpu(p1).oper[2]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[2]^);
  716. exit;
  717. end;
  718. A_IMUL:
  719. Result := (taicpu(p1).oper[taicpu(p1).ops-1]^.typ=top_reg) and RegInOp(reg,taicpu(p1).oper[taicpu(p1).ops-1]^);
  720. else
  721. ;
  722. end;
  723. if Result then
  724. exit;
  725. with insprop[taicpu(p1).opcode] do
  726. begin
  727. if getregtype(reg)=R_INTREGISTER then
  728. begin
  729. case getsupreg(reg) of
  730. RS_EAX:
  731. if [Ch_WEAX,Ch_RWEAX,Ch_MEAX]*Ch<>[] then
  732. begin
  733. Result := True;
  734. exit
  735. end;
  736. RS_ECX:
  737. if [Ch_WECX,Ch_RWECX,Ch_MECX]*Ch<>[] then
  738. begin
  739. Result := True;
  740. exit
  741. end;
  742. RS_EDX:
  743. if [Ch_WEDX,Ch_RWEDX,Ch_MEDX]*Ch<>[] then
  744. begin
  745. Result := True;
  746. exit
  747. end;
  748. RS_EBX:
  749. if [Ch_WEBX,Ch_RWEBX,Ch_MEBX]*Ch<>[] then
  750. begin
  751. Result := True;
  752. exit
  753. end;
  754. RS_ESP:
  755. if [Ch_WESP,Ch_RWESP,Ch_MESP]*Ch<>[] then
  756. begin
  757. Result := True;
  758. exit
  759. end;
  760. RS_EBP:
  761. if [Ch_WEBP,Ch_RWEBP,Ch_MEBP]*Ch<>[] then
  762. begin
  763. Result := True;
  764. exit
  765. end;
  766. RS_ESI:
  767. if [Ch_WESI,Ch_RWESI,Ch_MESI]*Ch<>[] then
  768. begin
  769. Result := True;
  770. exit
  771. end;
  772. RS_EDI:
  773. if [Ch_WEDI,Ch_RWEDI,Ch_MEDI]*Ch<>[] then
  774. begin
  775. Result := True;
  776. exit
  777. end;
  778. end;
  779. end;
  780. if ([CH_RWOP1,CH_WOP1,CH_MOP1]*Ch<>[]) and reginop(reg,taicpu(p1).oper[0]^) then
  781. begin
  782. Result := true;
  783. exit
  784. end;
  785. if ([Ch_RWOP2,Ch_WOP2,Ch_MOP2]*Ch<>[]) and reginop(reg,taicpu(p1).oper[1]^) then
  786. begin
  787. Result := true;
  788. exit
  789. end;
  790. if ([Ch_RWOP3,Ch_WOP3,Ch_MOP3]*Ch<>[]) and reginop(reg,taicpu(p1).oper[2]^) then
  791. begin
  792. Result := true;
  793. exit
  794. end;
  795. if ([Ch_RWOP4,Ch_WOP4,Ch_MOP4]*Ch<>[]) and reginop(reg,taicpu(p1).oper[3]^) then
  796. begin
  797. Result := true;
  798. exit
  799. end;
  800. end;
  801. end;
  802. {$ifdef DEBUG_AOPTCPU}
  803. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);
  804. begin
  805. asml.insertbefore(tai_comment.Create(strpnew(s)), p);
  806. end;
  807. function debug_tostr(i: tcgint): string; inline;
  808. begin
  809. Result := tostr(i);
  810. end;
  811. function debug_regname(r: TRegister): string; inline;
  812. begin
  813. Result := '%' + std_regname(r);
  814. end;
  815. { Debug output function - creates a string representation of an operator }
  816. function debug_operstr(oper: TOper): string;
  817. begin
  818. case oper.typ of
  819. top_const:
  820. Result := '$' + debug_tostr(oper.val);
  821. top_reg:
  822. Result := debug_regname(oper.reg);
  823. top_ref:
  824. begin
  825. if oper.ref^.offset <> 0 then
  826. Result := debug_tostr(oper.ref^.offset) + '('
  827. else
  828. Result := '(';
  829. if (oper.ref^.base <> NR_INVALID) and (oper.ref^.base <> NR_NO) then
  830. begin
  831. Result := Result + debug_regname(oper.ref^.base);
  832. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  833. Result := Result + ',' + debug_regname(oper.ref^.index);
  834. end
  835. else
  836. if (oper.ref^.index <> NR_INVALID) and (oper.ref^.index <> NR_NO) then
  837. Result := Result + debug_regname(oper.ref^.index);
  838. if (oper.ref^.scalefactor > 1) then
  839. Result := Result + ',' + debug_tostr(oper.ref^.scalefactor) + ')'
  840. else
  841. Result := Result + ')';
  842. end;
  843. else
  844. Result := '[UNKNOWN]';
  845. end;
  846. end;
  847. function debug_op2str(opcode: tasmop): string; inline;
  848. begin
  849. Result := std_op2str[opcode];
  850. end;
  851. function debug_opsize2str(opsize: topsize): string; inline;
  852. begin
  853. Result := gas_opsize2str[opsize];
  854. end;
  855. {$else DEBUG_AOPTCPU}
  856. procedure TX86AsmOptimizer.DebugMsg(const s: string;p : tai);inline;
  857. begin
  858. end;
  859. function debug_tostr(i: tcgint): string; inline;
  860. begin
  861. Result := '';
  862. end;
  863. function debug_regname(r: TRegister): string; inline;
  864. begin
  865. Result := '';
  866. end;
  867. function debug_operstr(oper: TOper): string; inline;
  868. begin
  869. Result := '';
  870. end;
  871. function debug_op2str(opcode: tasmop): string; inline;
  872. begin
  873. Result := '';
  874. end;
  875. function debug_opsize2str(opsize: topsize): string; inline;
  876. begin
  877. Result := '';
  878. end;
  879. {$endif DEBUG_AOPTCPU}
  880. class function TX86AsmOptimizer.IsMOVZXAcceptable: Boolean; inline;
  881. begin
  882. {$ifdef x86_64}
  883. { Always fine on x86-64 }
  884. Result := True;
  885. {$else x86_64}
  886. Result :=
  887. {$ifdef i8086}
  888. (current_settings.cputype >= cpu_386) and
  889. {$endif i8086}
  890. (
  891. { Always accept if optimising for size }
  892. (cs_opt_size in current_settings.optimizerswitches) or
  893. { From the Pentium II onwards, MOVZX only takes 1 cycle. [Kit] }
  894. (current_settings.optimizecputype >= cpu_Pentium2)
  895. );
  896. {$endif x86_64}
  897. end;
  898. function TX86AsmOptimizer.Reg1WriteOverwritesReg2Entirely(reg1, reg2: tregister): boolean;
  899. begin
  900. if not SuperRegistersEqual(reg1,reg2) then
  901. exit(false);
  902. if getregtype(reg1)<>R_INTREGISTER then
  903. exit(true); {because SuperRegisterEqual is true}
  904. case getsubreg(reg1) of
  905. { A write to R_SUBL doesn't change R_SUBH and if reg2 is R_SUBW or
  906. higher, it preserves the high bits, so the new value depends on
  907. reg2's previous value. In other words, it is equivalent to doing:
  908. reg2 := (reg2 and $ffffff00) or byte(reg1); }
  909. R_SUBL:
  910. exit(getsubreg(reg2)=R_SUBL);
  911. { A write to R_SUBH doesn't change R_SUBL and if reg2 is R_SUBW or
  912. higher, it actually does a:
  913. reg2 := (reg2 and $ffff00ff) or (reg1 and $ff00); }
  914. R_SUBH:
  915. exit(getsubreg(reg2)=R_SUBH);
  916. { If reg2 is R_SUBD or larger, a write to R_SUBW preserves the high 16
  917. bits of reg2:
  918. reg2 := (reg2 and $ffff0000) or word(reg1); }
  919. R_SUBW:
  920. exit(getsubreg(reg2) in [R_SUBL,R_SUBH,R_SUBW]);
  921. { a write to R_SUBD always overwrites every other subregister,
  922. because it clears the high 32 bits of R_SUBQ on x86_64 }
  923. R_SUBD,
  924. R_SUBQ:
  925. exit(true);
  926. else
  927. internalerror(2017042801);
  928. end;
  929. end;
  930. function TX86AsmOptimizer.Reg1ReadDependsOnReg2(reg1, reg2: tregister): boolean;
  931. begin
  932. if not SuperRegistersEqual(reg1,reg2) then
  933. exit(false);
  934. if getregtype(reg1)<>R_INTREGISTER then
  935. exit(true); {because SuperRegisterEqual is true}
  936. case getsubreg(reg1) of
  937. R_SUBL:
  938. exit(getsubreg(reg2)<>R_SUBH);
  939. R_SUBH:
  940. exit(getsubreg(reg2)<>R_SUBL);
  941. R_SUBW,
  942. R_SUBD,
  943. R_SUBQ:
  944. exit(true);
  945. else
  946. internalerror(2017042802);
  947. end;
  948. end;
  949. function TX86AsmOptimizer.PrePeepholeOptSxx(var p : tai) : boolean;
  950. var
  951. hp1 : tai;
  952. l : TCGInt;
  953. begin
  954. result:=false;
  955. { changes the code sequence
  956. shr/sar const1, x
  957. shl const2, x
  958. to
  959. either "sar/and", "shl/and" or just "and" depending on const1 and const2 }
  960. if GetNextInstruction(p, hp1) and
  961. MatchInstruction(hp1,A_SHL,[]) and
  962. (taicpu(p).oper[0]^.typ = top_const) and
  963. (taicpu(hp1).oper[0]^.typ = top_const) and
  964. (taicpu(hp1).opsize = taicpu(p).opsize) and
  965. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[1]^.typ) and
  966. OpsEqual(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^) then
  967. begin
  968. if (taicpu(p).oper[0]^.val > taicpu(hp1).oper[0]^.val) and
  969. not(cs_opt_size in current_settings.optimizerswitches) then
  970. begin
  971. { shr/sar const1, %reg
  972. shl const2, %reg
  973. with const1 > const2 }
  974. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  975. taicpu(hp1).opcode := A_AND;
  976. l := (1 shl (taicpu(hp1).oper[0]^.val)) - 1;
  977. case taicpu(p).opsize Of
  978. S_B: taicpu(hp1).loadConst(0,l Xor $ff);
  979. S_W: taicpu(hp1).loadConst(0,l Xor $ffff);
  980. S_L: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffff));
  981. S_Q: taicpu(hp1).loadConst(0,l Xor tcgint($ffffffffffffffff));
  982. else
  983. Internalerror(2017050703)
  984. end;
  985. end
  986. else if (taicpu(p).oper[0]^.val<taicpu(hp1).oper[0]^.val) and
  987. not(cs_opt_size in current_settings.optimizerswitches) then
  988. begin
  989. { shr/sar const1, %reg
  990. shl const2, %reg
  991. with const1 < const2 }
  992. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val-taicpu(p).oper[0]^.val);
  993. taicpu(p).opcode := A_AND;
  994. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  995. case taicpu(p).opsize Of
  996. S_B: taicpu(p).loadConst(0,l Xor $ff);
  997. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  998. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  999. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1000. else
  1001. Internalerror(2017050702)
  1002. end;
  1003. end
  1004. else if (taicpu(p).oper[0]^.val = taicpu(hp1).oper[0]^.val) then
  1005. begin
  1006. { shr/sar const1, %reg
  1007. shl const2, %reg
  1008. with const1 = const2 }
  1009. taicpu(p).opcode := A_AND;
  1010. l := (1 shl (taicpu(p).oper[0]^.val))-1;
  1011. case taicpu(p).opsize Of
  1012. S_B: taicpu(p).loadConst(0,l Xor $ff);
  1013. S_W: taicpu(p).loadConst(0,l Xor $ffff);
  1014. S_L: taicpu(p).loadConst(0,l Xor tcgint($ffffffff));
  1015. S_Q: taicpu(p).loadConst(0,l Xor tcgint($ffffffffffffffff));
  1016. else
  1017. Internalerror(2017050701)
  1018. end;
  1019. RemoveInstruction(hp1);
  1020. end;
  1021. end;
  1022. end;
  1023. function TX86AsmOptimizer.PrePeepholeOptIMUL(var p : tai) : boolean;
  1024. var
  1025. opsize : topsize;
  1026. hp1 : tai;
  1027. tmpref : treference;
  1028. ShiftValue : Cardinal;
  1029. BaseValue : TCGInt;
  1030. begin
  1031. result:=false;
  1032. opsize:=taicpu(p).opsize;
  1033. { changes certain "imul const, %reg"'s to lea sequences }
  1034. if (MatchOpType(taicpu(p),top_const,top_reg) or
  1035. MatchOpType(taicpu(p),top_const,top_reg,top_reg)) and
  1036. (opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) then
  1037. if (taicpu(p).oper[0]^.val = 1) then
  1038. if (taicpu(p).ops = 2) then
  1039. { remove "imul $1, reg" }
  1040. begin
  1041. DebugMsg(SPeepholeOptimization + 'Imul2Nop done',p);
  1042. Result := RemoveCurrentP(p);
  1043. end
  1044. else
  1045. { change "imul $1, reg1, reg2" to "mov reg1, reg2" }
  1046. begin
  1047. hp1 := taicpu.Op_Reg_Reg(A_MOV, opsize, taicpu(p).oper[1]^.reg,taicpu(p).oper[2]^.reg);
  1048. InsertLLItem(p.previous, p.next, hp1);
  1049. DebugMsg(SPeepholeOptimization + 'Imul2Mov done',p);
  1050. p.free;
  1051. p := hp1;
  1052. end
  1053. else if ((taicpu(p).ops <= 2) or
  1054. (taicpu(p).oper[2]^.typ = Top_Reg)) and
  1055. not(cs_opt_size in current_settings.optimizerswitches) and
  1056. (not(GetNextInstruction(p, hp1)) or
  1057. not((tai(hp1).typ = ait_instruction) and
  1058. ((taicpu(hp1).opcode=A_Jcc) and
  1059. (taicpu(hp1).condition in [C_O,C_NO])))) then
  1060. begin
  1061. {
  1062. imul X, reg1, reg2 to
  1063. lea (reg1,reg1,Y), reg2
  1064. shl ZZ,reg2
  1065. imul XX, reg1 to
  1066. lea (reg1,reg1,YY), reg1
  1067. shl ZZ,reg2
  1068. This optimziation makes sense for pretty much every x86, except the VIA Nano3000: it has IMUL latency 2, lea/shl pair as well,
  1069. it does not exist as a separate optimization target in FPC though.
  1070. This optimziation can be applied as long as only two bits are set in the constant and those two bits are separated by
  1071. at most two zeros
  1072. }
  1073. reference_reset(tmpref,1,[]);
  1074. if (PopCnt(QWord(taicpu(p).oper[0]^.val))=2) and (BsrQWord(taicpu(p).oper[0]^.val)-BsfQWord(taicpu(p).oper[0]^.val)<=3) then
  1075. begin
  1076. ShiftValue:=BsfQWord(taicpu(p).oper[0]^.val);
  1077. BaseValue:=taicpu(p).oper[0]^.val shr ShiftValue;
  1078. TmpRef.base := taicpu(p).oper[1]^.reg;
  1079. TmpRef.index := taicpu(p).oper[1]^.reg;
  1080. if not(BaseValue in [3,5,9]) then
  1081. Internalerror(2018110101);
  1082. TmpRef.ScaleFactor := BaseValue-1;
  1083. if (taicpu(p).ops = 2) then
  1084. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[1]^.reg)
  1085. else
  1086. hp1 := taicpu.op_ref_reg(A_LEA, opsize, TmpRef, taicpu(p).oper[2]^.reg);
  1087. AsmL.InsertAfter(hp1,p);
  1088. DebugMsg(SPeepholeOptimization + 'Imul2LeaShl done',p);
  1089. taicpu(hp1).fileinfo:=taicpu(p).fileinfo;
  1090. RemoveCurrentP(p, hp1);
  1091. if ShiftValue>0 then
  1092. AsmL.InsertAfter(taicpu.op_const_reg(A_SHL, opsize, ShiftValue, taicpu(hp1).oper[1]^.reg),hp1);
  1093. end;
  1094. end;
  1095. end;
  1096. function TX86AsmOptimizer.PrePeepholeOptAND(var p : tai) : boolean;
  1097. begin
  1098. Result := False;
  1099. if MatchOperand(taicpu(p).oper[0]^, 0) and
  1100. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  1101. begin
  1102. DebugMsg(SPeepholeOptimization + 'AND 0 -> MOV 0', p);
  1103. taicpu(p).opcode := A_MOV;
  1104. Result := True;
  1105. end;
  1106. end;
  1107. function TX86AsmOptimizer.RegLoadedWithNewValue(reg: tregister; hp: tai): boolean;
  1108. var
  1109. p: taicpu absolute hp;
  1110. i: Integer;
  1111. begin
  1112. Result := False;
  1113. if not assigned(hp) or
  1114. (hp.typ <> ait_instruction) then
  1115. Exit;
  1116. // p := taicpu(hp);
  1117. Prefetch(insprop[p.opcode]);
  1118. if SuperRegistersEqual(reg,NR_DEFAULTFLAGS) then
  1119. with insprop[p.opcode] do
  1120. begin
  1121. case getsubreg(reg) of
  1122. R_SUBW,R_SUBD,R_SUBQ:
  1123. Result:=
  1124. RegLoadedWithNewValue(NR_CARRYFLAG,hp) and
  1125. RegLoadedWithNewValue(NR_PARITYFLAG,hp) and
  1126. RegLoadedWithNewValue(NR_AUXILIARYFLAG,hp) and
  1127. RegLoadedWithNewValue(NR_ZEROFLAG,hp) and
  1128. RegLoadedWithNewValue(NR_SIGNFLAG,hp) and
  1129. RegLoadedWithNewValue(NR_OVERFLOWFLAG,hp);
  1130. R_SUBFLAGCARRY:
  1131. Result:=[Ch_W0CarryFlag,Ch_W1CarryFlag,Ch_WCarryFlag,Ch_WUCarryFlag,Ch_WFlags]*Ch<>[];
  1132. R_SUBFLAGPARITY:
  1133. Result:=[Ch_W0ParityFlag,Ch_W1ParityFlag,Ch_WParityFlag,Ch_WUParityFlag,Ch_WFlags]*Ch<>[];
  1134. R_SUBFLAGAUXILIARY:
  1135. Result:=[Ch_W0AuxiliaryFlag,Ch_W1AuxiliaryFlag,Ch_WAuxiliaryFlag,Ch_WUAuxiliaryFlag,Ch_WFlags]*Ch<>[];
  1136. R_SUBFLAGZERO:
  1137. Result:=[Ch_W0ZeroFlag,Ch_W1ZeroFlag,Ch_WZeroFlag,Ch_WUZeroFlag,Ch_WFlags]*Ch<>[];
  1138. R_SUBFLAGSIGN:
  1139. Result:=[Ch_W0SignFlag,Ch_W1SignFlag,Ch_WSignFlag,Ch_WUSignFlag,Ch_WFlags]*Ch<>[];
  1140. R_SUBFLAGOVERFLOW:
  1141. Result:=[Ch_W0OverflowFlag,Ch_W1OverflowFlag,Ch_WOverflowFlag,Ch_WUOverflowFlag,Ch_WFlags]*Ch<>[];
  1142. R_SUBFLAGINTERRUPT:
  1143. Result:=[Ch_W0IntFlag,Ch_W1IntFlag,Ch_WFlags]*Ch<>[];
  1144. R_SUBFLAGDIRECTION:
  1145. Result:=[Ch_W0DirFlag,Ch_W1DirFlag,Ch_WFlags]*Ch<>[];
  1146. else
  1147. begin
  1148. writeln(getsubreg(reg));
  1149. internalerror(2017050501);
  1150. end;
  1151. end;
  1152. exit;
  1153. end;
  1154. { Handle special cases first }
  1155. case p.opcode of
  1156. A_MOV, A_MOVZX, A_MOVSX, A_LEA, A_VMOVSS, A_VMOVSD, A_VMOVAPD,
  1157. A_VMOVAPS, A_VMOVQ, A_MOVSS, A_MOVSD, A_MOVQ, A_MOVAPD, A_MOVAPS:
  1158. begin
  1159. Result :=
  1160. (p.ops=2) and { A_MOVSD can have zero operands, so this check is needed }
  1161. (p.oper[1]^.typ = top_reg) and
  1162. (Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)) and
  1163. (
  1164. (p.oper[0]^.typ = top_const) or
  1165. (
  1166. (p.oper[0]^.typ = top_reg) and
  1167. not(Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg))
  1168. ) or (
  1169. (p.oper[0]^.typ = top_ref) and
  1170. not RegInRef(reg,p.oper[0]^.ref^)
  1171. )
  1172. );
  1173. end;
  1174. A_MUL, A_IMUL:
  1175. Result :=
  1176. (
  1177. (p.ops=3) and { IMUL only }
  1178. (Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg,reg)) and
  1179. (
  1180. (
  1181. (p.oper[1]^.typ=top_reg) and
  1182. not Reg1ReadDependsOnReg2(p.oper[1]^.reg,reg)
  1183. ) or (
  1184. (p.oper[1]^.typ=top_ref) and
  1185. not RegInRef(reg,p.oper[1]^.ref^)
  1186. )
  1187. )
  1188. ) or (
  1189. (
  1190. (p.ops=1) and
  1191. (
  1192. (
  1193. (
  1194. (p.oper[0]^.typ=top_reg) and
  1195. not Reg1ReadDependsOnReg2(p.oper[0]^.reg,reg)
  1196. )
  1197. ) or (
  1198. (p.oper[0]^.typ=top_ref) and
  1199. not RegInRef(reg,p.oper[0]^.ref^)
  1200. )
  1201. ) and (
  1202. (
  1203. (p.opsize=S_B) and
  1204. Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and
  1205. not Reg1ReadDependsOnReg2(NR_AL,reg)
  1206. ) or (
  1207. (p.opsize=S_W) and
  1208. Reg1WriteOverwritesReg2Entirely(NR_DX,reg)
  1209. ) or (
  1210. (p.opsize=S_L) and
  1211. Reg1WriteOverwritesReg2Entirely(NR_EDX,reg)
  1212. {$ifdef x86_64}
  1213. ) or (
  1214. (p.opsize=S_Q) and
  1215. Reg1WriteOverwritesReg2Entirely(NR_RDX,reg)
  1216. {$endif x86_64}
  1217. )
  1218. )
  1219. )
  1220. );
  1221. A_CBW:
  1222. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg) and not(Reg1ReadDependsOnReg2(NR_AL,reg));
  1223. {$ifndef x86_64}
  1224. A_LDS:
  1225. Result := (reg=NR_DS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1226. A_LES:
  1227. Result := (reg=NR_ES) and not(RegInRef(reg,p.oper[0]^.ref^));
  1228. {$endif not x86_64}
  1229. A_LFS:
  1230. Result := (reg=NR_FS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1231. A_LGS:
  1232. Result := (reg=NR_GS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1233. A_LSS:
  1234. Result := (reg=NR_SS) and not(RegInRef(reg,p.oper[0]^.ref^));
  1235. A_LAHF{$ifndef x86_64}, A_AAM{$endif not x86_64}:
  1236. Result := Reg1WriteOverwritesReg2Entirely(NR_AH,reg);
  1237. A_LODSB:
  1238. Result := Reg1WriteOverwritesReg2Entirely(NR_AL,reg);
  1239. A_LODSW:
  1240. Result := Reg1WriteOverwritesReg2Entirely(NR_AX,reg);
  1241. {$ifdef x86_64}
  1242. A_LODSQ:
  1243. Result := Reg1WriteOverwritesReg2Entirely(NR_RAX,reg);
  1244. {$endif x86_64}
  1245. A_LODSD:
  1246. Result := Reg1WriteOverwritesReg2Entirely(NR_EAX,reg);
  1247. A_FSTSW, A_FNSTSW:
  1248. Result := (p.oper[0]^.typ=top_reg) and Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg,reg);
  1249. else
  1250. begin
  1251. with insprop[p.opcode] do
  1252. begin
  1253. if (
  1254. { xor %reg,%reg etc. is classed as a new value }
  1255. (([Ch_NoReadIfEqualRegs]*Ch)<>[]) and
  1256. MatchOpType(p, top_reg, top_reg) and
  1257. (p.oper[0]^.reg = p.oper[1]^.reg) and
  1258. Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg,reg)
  1259. ) then
  1260. begin
  1261. Result := True;
  1262. Exit;
  1263. end;
  1264. { Make sure the entire register is overwritten }
  1265. if (getregtype(reg) = R_INTREGISTER) then
  1266. begin
  1267. if (p.ops > 0) then
  1268. begin
  1269. if RegInOp(reg, p.oper[0]^) then
  1270. begin
  1271. if (p.oper[0]^.typ = top_ref) then
  1272. begin
  1273. if RegInRef(reg, p.oper[0]^.ref^) then
  1274. begin
  1275. Result := False;
  1276. Exit;
  1277. end;
  1278. end
  1279. else if (p.oper[0]^.typ = top_reg) then
  1280. begin
  1281. if ([Ch_ROp1, Ch_RWOp1, Ch_MOp1]*Ch<>[]) then
  1282. begin
  1283. Result := False;
  1284. Exit;
  1285. end
  1286. else if ([Ch_WOp1]*Ch<>[]) then
  1287. begin
  1288. if Reg1WriteOverwritesReg2Entirely(p.oper[0]^.reg, reg) then
  1289. Result := True
  1290. else
  1291. begin
  1292. Result := False;
  1293. Exit;
  1294. end;
  1295. end;
  1296. end;
  1297. end;
  1298. if (p.ops > 1) then
  1299. begin
  1300. if RegInOp(reg, p.oper[1]^) then
  1301. begin
  1302. if (p.oper[1]^.typ = top_ref) then
  1303. begin
  1304. if RegInRef(reg, p.oper[1]^.ref^) then
  1305. begin
  1306. Result := False;
  1307. Exit;
  1308. end;
  1309. end
  1310. else if (p.oper[1]^.typ = top_reg) then
  1311. begin
  1312. if ([Ch_ROp2, Ch_RWOp2, Ch_MOp2]*Ch<>[]) then
  1313. begin
  1314. Result := False;
  1315. Exit;
  1316. end
  1317. else if ([Ch_WOp2]*Ch<>[]) then
  1318. begin
  1319. if Reg1WriteOverwritesReg2Entirely(p.oper[1]^.reg, reg) then
  1320. Result := True
  1321. else
  1322. begin
  1323. Result := False;
  1324. Exit;
  1325. end;
  1326. end;
  1327. end;
  1328. end;
  1329. if (p.ops > 2) then
  1330. begin
  1331. if RegInOp(reg, p.oper[2]^) then
  1332. begin
  1333. if (p.oper[2]^.typ = top_ref) then
  1334. begin
  1335. if RegInRef(reg, p.oper[2]^.ref^) then
  1336. begin
  1337. Result := False;
  1338. Exit;
  1339. end;
  1340. end
  1341. else if (p.oper[2]^.typ = top_reg) then
  1342. begin
  1343. if ([Ch_ROp3, Ch_RWOp3, Ch_MOp3]*Ch<>[]) then
  1344. begin
  1345. Result := False;
  1346. Exit;
  1347. end
  1348. else if ([Ch_WOp3]*Ch<>[]) then
  1349. begin
  1350. if Reg1WriteOverwritesReg2Entirely(p.oper[2]^.reg, reg) then
  1351. Result := True
  1352. else
  1353. begin
  1354. Result := False;
  1355. Exit;
  1356. end;
  1357. end;
  1358. end;
  1359. end;
  1360. if (p.ops > 3) and RegInOp(reg, p.oper[3]^) then
  1361. begin
  1362. if (p.oper[3]^.typ = top_ref) then
  1363. begin
  1364. if RegInRef(reg, p.oper[3]^.ref^) then
  1365. begin
  1366. Result := False;
  1367. Exit;
  1368. end;
  1369. end
  1370. else if (p.oper[3]^.typ = top_reg) then
  1371. begin
  1372. if ([Ch_ROp4, Ch_RWOp4, Ch_MOp4]*Ch<>[]) then
  1373. begin
  1374. Result := False;
  1375. Exit;
  1376. end
  1377. else if ([Ch_WOp4]*Ch<>[]) then
  1378. begin
  1379. if Reg1WriteOverwritesReg2Entirely(p.oper[3]^.reg, reg) then
  1380. Result := True
  1381. else
  1382. begin
  1383. Result := False;
  1384. Exit;
  1385. end;
  1386. end;
  1387. end;
  1388. end;
  1389. end;
  1390. end;
  1391. end;
  1392. { Don't do these ones first in case an input operand is equal to an explicit output registers }
  1393. case getsupreg(reg) of
  1394. RS_EAX:
  1395. if ([Ch_WEAX{$ifdef x86_64},Ch_WRAX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EAX, reg) then
  1396. begin
  1397. Result := True;
  1398. Exit;
  1399. end;
  1400. RS_ECX:
  1401. if ([Ch_WECX{$ifdef x86_64},Ch_WRCX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ECX, reg) then
  1402. begin
  1403. Result := True;
  1404. Exit;
  1405. end;
  1406. RS_EDX:
  1407. if ([Ch_REDX{$ifdef x86_64},Ch_WRDX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDX, reg) then
  1408. begin
  1409. Result := True;
  1410. Exit;
  1411. end;
  1412. RS_EBX:
  1413. if ([Ch_WEBX{$ifdef x86_64},Ch_WRBX{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBX, reg) then
  1414. begin
  1415. Result := True;
  1416. Exit;
  1417. end;
  1418. RS_ESP:
  1419. if ([Ch_WESP{$ifdef x86_64},Ch_WRSP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESP, reg) then
  1420. begin
  1421. Result := True;
  1422. Exit;
  1423. end;
  1424. RS_EBP:
  1425. if ([Ch_WEBP{$ifdef x86_64},Ch_WRBP{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EBP, reg) then
  1426. begin
  1427. Result := True;
  1428. Exit;
  1429. end;
  1430. RS_ESI:
  1431. if ([Ch_WESI{$ifdef x86_64},Ch_WRSI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_ESI, reg) then
  1432. begin
  1433. Result := True;
  1434. Exit;
  1435. end;
  1436. RS_EDI:
  1437. if ([Ch_WEDI{$ifdef x86_64},Ch_WRDI{$endif x86_64}]*Ch<>[]) and Reg1WriteOverwritesReg2Entirely(NR_EDI, reg) then
  1438. begin
  1439. Result := True;
  1440. Exit;
  1441. end;
  1442. else
  1443. ;
  1444. end;
  1445. end;
  1446. end;
  1447. end;
  1448. end;
  1449. end;
  1450. class function TX86AsmOptimizer.IsExitCode(p : tai) : boolean;
  1451. var
  1452. hp2,hp3 : tai;
  1453. begin
  1454. { some x86-64 issue a NOP before the real exit code }
  1455. if MatchInstruction(p,A_NOP,[]) then
  1456. GetNextInstruction(p,p);
  1457. result:=assigned(p) and (p.typ=ait_instruction) and
  1458. ((taicpu(p).opcode = A_RET) or
  1459. ((taicpu(p).opcode=A_LEAVE) and
  1460. GetNextInstruction(p,hp2) and
  1461. MatchInstruction(hp2,A_RET,[S_NO])
  1462. ) or
  1463. (((taicpu(p).opcode=A_LEA) and
  1464. MatchOpType(taicpu(p),top_ref,top_reg) and
  1465. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  1466. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1467. ) and
  1468. GetNextInstruction(p,hp2) and
  1469. MatchInstruction(hp2,A_RET,[S_NO])
  1470. ) or
  1471. ((((taicpu(p).opcode=A_MOV) and
  1472. MatchOpType(taicpu(p),top_reg,top_reg) and
  1473. (taicpu(p).oper[0]^.reg=current_procinfo.framepointer) and
  1474. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)) or
  1475. ((taicpu(p).opcode=A_LEA) and
  1476. MatchOpType(taicpu(p),top_ref,top_reg) and
  1477. (taicpu(p).oper[0]^.ref^.base=current_procinfo.framepointer) and
  1478. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG)
  1479. )
  1480. ) and
  1481. GetNextInstruction(p,hp2) and
  1482. MatchInstruction(hp2,A_POP,[reg2opsize(current_procinfo.framepointer)]) and
  1483. MatchOpType(taicpu(hp2),top_reg) and
  1484. (taicpu(hp2).oper[0]^.reg=current_procinfo.framepointer) and
  1485. GetNextInstruction(hp2,hp3) and
  1486. MatchInstruction(hp3,A_RET,[S_NO])
  1487. )
  1488. );
  1489. end;
  1490. class function TX86AsmOptimizer.isFoldableArithOp(hp1: taicpu; reg: tregister): boolean;
  1491. begin
  1492. isFoldableArithOp := False;
  1493. case hp1.opcode of
  1494. A_ADD,A_SUB,A_OR,A_XOR,A_AND,A_SHL,A_SHR,A_SAR:
  1495. isFoldableArithOp :=
  1496. ((taicpu(hp1).oper[0]^.typ = top_const) or
  1497. ((taicpu(hp1).oper[0]^.typ = top_reg) and
  1498. (taicpu(hp1).oper[0]^.reg <> reg))) and
  1499. (taicpu(hp1).oper[1]^.typ = top_reg) and
  1500. (taicpu(hp1).oper[1]^.reg = reg);
  1501. A_INC,A_DEC,A_NEG,A_NOT:
  1502. isFoldableArithOp :=
  1503. (taicpu(hp1).oper[0]^.typ = top_reg) and
  1504. (taicpu(hp1).oper[0]^.reg = reg);
  1505. else
  1506. ;
  1507. end;
  1508. end;
  1509. procedure TX86AsmOptimizer.RemoveLastDeallocForFuncRes(p: tai);
  1510. procedure DoRemoveLastDeallocForFuncRes( supreg: tsuperregister);
  1511. var
  1512. hp2: tai;
  1513. begin
  1514. hp2 := p;
  1515. repeat
  1516. hp2 := tai(hp2.previous);
  1517. if assigned(hp2) and
  1518. (hp2.typ = ait_regalloc) and
  1519. (tai_regalloc(hp2).ratype=ra_dealloc) and
  1520. (getregtype(tai_regalloc(hp2).reg) = R_INTREGISTER) and
  1521. (getsupreg(tai_regalloc(hp2).reg) = supreg) then
  1522. begin
  1523. RemoveInstruction(hp2);
  1524. break;
  1525. end;
  1526. until not(assigned(hp2)) or regInInstruction(newreg(R_INTREGISTER,supreg,R_SUBWHOLE),hp2);
  1527. end;
  1528. begin
  1529. case current_procinfo.procdef.returndef.typ of
  1530. arraydef,recorddef,pointerdef,
  1531. stringdef,enumdef,procdef,objectdef,errordef,
  1532. filedef,setdef,procvardef,
  1533. classrefdef,forwarddef:
  1534. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1535. orddef:
  1536. if current_procinfo.procdef.returndef.size <> 0 then
  1537. begin
  1538. DoRemoveLastDeallocForFuncRes(RS_EAX);
  1539. { for int64/qword }
  1540. if current_procinfo.procdef.returndef.size = 8 then
  1541. DoRemoveLastDeallocForFuncRes(RS_EDX);
  1542. end;
  1543. else
  1544. ;
  1545. end;
  1546. end;
  1547. function TX86AsmOptimizer.OptPass1_V_MOVAP(var p : tai) : boolean;
  1548. var
  1549. hp1,hp2 : tai;
  1550. begin
  1551. result:=false;
  1552. if MatchOpType(taicpu(p),top_reg,top_reg) then
  1553. begin
  1554. { vmova* reg1,reg1
  1555. =>
  1556. <nop> }
  1557. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  1558. begin
  1559. RemoveCurrentP(p);
  1560. result:=true;
  1561. exit;
  1562. end
  1563. else if GetNextInstruction(p,hp1) then
  1564. begin
  1565. if MatchInstruction(hp1,[taicpu(p).opcode],[S_NO]) and
  1566. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1567. begin
  1568. { vmova* reg1,reg2
  1569. vmova* reg2,reg3
  1570. dealloc reg2
  1571. =>
  1572. vmova* reg1,reg3 }
  1573. TransferUsedRegs(TmpUsedRegs);
  1574. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1575. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  1576. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1577. begin
  1578. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 1',p);
  1579. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1580. RemoveInstruction(hp1);
  1581. result:=true;
  1582. exit;
  1583. end
  1584. { special case:
  1585. vmova* reg1,<op>
  1586. vmova* <op>,reg1
  1587. =>
  1588. vmova* reg1,<op> }
  1589. else if MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  1590. ((taicpu(p).oper[0]^.typ<>top_ref) or
  1591. (not(vol_read in taicpu(p).oper[0]^.ref^.volatility))
  1592. ) then
  1593. begin
  1594. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVA*2(V)MOVA* 2',p);
  1595. RemoveInstruction(hp1);
  1596. result:=true;
  1597. exit;
  1598. end
  1599. end
  1600. else if ((MatchInstruction(p,[A_MOVAPS,A_VMOVAPS],[S_NO]) and
  1601. MatchInstruction(hp1,[A_MOVSS,A_VMOVSS],[S_NO])) or
  1602. ((MatchInstruction(p,[A_MOVAPD,A_VMOVAPD],[S_NO]) and
  1603. MatchInstruction(hp1,[A_MOVSD,A_VMOVSD],[S_NO])))
  1604. ) and
  1605. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  1606. begin
  1607. { vmova* reg1,reg2
  1608. vmovs* reg2,<op>
  1609. dealloc reg2
  1610. =>
  1611. vmovs* reg1,reg3 }
  1612. TransferUsedRegs(TmpUsedRegs);
  1613. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1614. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  1615. begin
  1616. DebugMsg(SPeepholeOptimization + '(V)MOVA*(V)MOVS*2(V)MOVS* 1',p);
  1617. taicpu(p).opcode:=taicpu(hp1).opcode;
  1618. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  1619. RemoveInstruction(hp1);
  1620. result:=true;
  1621. exit;
  1622. end
  1623. end;
  1624. end;
  1625. if GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  1626. begin
  1627. if MatchInstruction(hp1,[A_VFMADDPD,
  1628. A_VFMADD132PD,
  1629. A_VFMADD132PS,
  1630. A_VFMADD132SD,
  1631. A_VFMADD132SS,
  1632. A_VFMADD213PD,
  1633. A_VFMADD213PS,
  1634. A_VFMADD213SD,
  1635. A_VFMADD213SS,
  1636. A_VFMADD231PD,
  1637. A_VFMADD231PS,
  1638. A_VFMADD231SD,
  1639. A_VFMADD231SS,
  1640. A_VFMADDSUB132PD,
  1641. A_VFMADDSUB132PS,
  1642. A_VFMADDSUB213PD,
  1643. A_VFMADDSUB213PS,
  1644. A_VFMADDSUB231PD,
  1645. A_VFMADDSUB231PS,
  1646. A_VFMSUB132PD,
  1647. A_VFMSUB132PS,
  1648. A_VFMSUB132SD,
  1649. A_VFMSUB132SS,
  1650. A_VFMSUB213PD,
  1651. A_VFMSUB213PS,
  1652. A_VFMSUB213SD,
  1653. A_VFMSUB213SS,
  1654. A_VFMSUB231PD,
  1655. A_VFMSUB231PS,
  1656. A_VFMSUB231SD,
  1657. A_VFMSUB231SS,
  1658. A_VFMSUBADD132PD,
  1659. A_VFMSUBADD132PS,
  1660. A_VFMSUBADD213PD,
  1661. A_VFMSUBADD213PS,
  1662. A_VFMSUBADD231PD,
  1663. A_VFMSUBADD231PS,
  1664. A_VFNMADD132PD,
  1665. A_VFNMADD132PS,
  1666. A_VFNMADD132SD,
  1667. A_VFNMADD132SS,
  1668. A_VFNMADD213PD,
  1669. A_VFNMADD213PS,
  1670. A_VFNMADD213SD,
  1671. A_VFNMADD213SS,
  1672. A_VFNMADD231PD,
  1673. A_VFNMADD231PS,
  1674. A_VFNMADD231SD,
  1675. A_VFNMADD231SS,
  1676. A_VFNMSUB132PD,
  1677. A_VFNMSUB132PS,
  1678. A_VFNMSUB132SD,
  1679. A_VFNMSUB132SS,
  1680. A_VFNMSUB213PD,
  1681. A_VFNMSUB213PS,
  1682. A_VFNMSUB213SD,
  1683. A_VFNMSUB213SS,
  1684. A_VFNMSUB231PD,
  1685. A_VFNMSUB231PS,
  1686. A_VFNMSUB231SD,
  1687. A_VFNMSUB231SS],[S_NO]) and
  1688. { we mix single and double opperations here because we assume that the compiler
  1689. generates vmovapd only after double operations and vmovaps only after single operations }
  1690. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[2]^) and
  1691. GetNextInstruction(hp1,hp2) and
  1692. MatchInstruction(hp2,[A_VMOVAPD,A_VMOVAPS,A_MOVAPD,A_MOVAPS],[S_NO]) and
  1693. MatchOperand(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) then
  1694. begin
  1695. TransferUsedRegs(TmpUsedRegs);
  1696. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1697. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1698. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1699. begin
  1700. taicpu(hp1).loadoper(2,taicpu(p).oper[0]^);
  1701. RemoveCurrentP(p, hp1); // <-- Is this actually safe? hp1 is not necessarily the next instruction. [Kit]
  1702. RemoveInstruction(hp2);
  1703. end;
  1704. end
  1705. else if (hp1.typ = ait_instruction) and
  1706. GetNextInstruction(hp1, hp2) and
  1707. MatchInstruction(hp2,taicpu(p).opcode,[]) and
  1708. OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  1709. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  1710. MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^) and
  1711. (((taicpu(p).opcode=A_MOVAPS) and
  1712. ((taicpu(hp1).opcode=A_ADDSS) or (taicpu(hp1).opcode=A_SUBSS) or
  1713. (taicpu(hp1).opcode=A_MULSS) or (taicpu(hp1).opcode=A_DIVSS))) or
  1714. ((taicpu(p).opcode=A_MOVAPD) and
  1715. ((taicpu(hp1).opcode=A_ADDSD) or (taicpu(hp1).opcode=A_SUBSD) or
  1716. (taicpu(hp1).opcode=A_MULSD) or (taicpu(hp1).opcode=A_DIVSD)))
  1717. ) then
  1718. { change
  1719. movapX reg,reg2
  1720. addsX/subsX/... reg3, reg2
  1721. movapX reg2,reg
  1722. to
  1723. addsX/subsX/... reg3,reg
  1724. }
  1725. begin
  1726. TransferUsedRegs(TmpUsedRegs);
  1727. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1728. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  1729. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  1730. begin
  1731. DebugMsg(SPeepholeOptimization + 'MovapXOpMovapX2Op ('+
  1732. debug_op2str(taicpu(p).opcode)+' '+
  1733. debug_op2str(taicpu(hp1).opcode)+' '+
  1734. debug_op2str(taicpu(hp2).opcode)+') done',p);
  1735. { we cannot eliminate the first move if
  1736. the operations uses the same register for source and dest }
  1737. if not(OpsEqual(taicpu(hp1).oper[1]^,taicpu(hp1).oper[0]^)) then
  1738. RemoveCurrentP(p, nil);
  1739. p:=hp1;
  1740. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  1741. RemoveInstruction(hp2);
  1742. result:=true;
  1743. end;
  1744. end;
  1745. end;
  1746. end;
  1747. end;
  1748. function TX86AsmOptimizer.OptPass1VOP(var p : tai) : boolean;
  1749. var
  1750. hp1 : tai;
  1751. begin
  1752. result:=false;
  1753. { replace
  1754. V<Op>X %mreg1,%mreg2,%mreg3
  1755. VMovX %mreg3,%mreg4
  1756. dealloc %mreg3
  1757. by
  1758. V<Op>X %mreg1,%mreg2,%mreg4
  1759. ?
  1760. }
  1761. if GetNextInstruction(p,hp1) and
  1762. { we mix single and double operations here because we assume that the compiler
  1763. generates vmovapd only after double operations and vmovaps only after single operations }
  1764. MatchInstruction(hp1,A_VMOVAPD,A_VMOVAPS,[S_NO]) and
  1765. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  1766. (taicpu(hp1).oper[1]^.typ=top_reg) then
  1767. begin
  1768. TransferUsedRegs(TmpUsedRegs);
  1769. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  1770. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  1771. begin
  1772. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  1773. DebugMsg(SPeepholeOptimization + 'VOpVmov2VOp done',p);
  1774. RemoveInstruction(hp1);
  1775. result:=true;
  1776. end;
  1777. end;
  1778. end;
  1779. { Replaces all references to AOldReg in a memory reference to ANewReg }
  1780. class function TX86AsmOptimizer.ReplaceRegisterInRef(var ref: TReference; const AOldReg, ANewReg: TRegister): Boolean;
  1781. begin
  1782. Result := False;
  1783. { For safety reasons, only check for exact register matches }
  1784. { Check base register }
  1785. if (ref.base = AOldReg) then
  1786. begin
  1787. ref.base := ANewReg;
  1788. Result := True;
  1789. end;
  1790. { Check index register }
  1791. if (ref.index = AOldReg) then
  1792. begin
  1793. ref.index := ANewReg;
  1794. Result := True;
  1795. end;
  1796. end;
  1797. { Replaces all references to AOldReg in an operand to ANewReg }
  1798. class function TX86AsmOptimizer.ReplaceRegisterInOper(const p: taicpu; const OperIdx: Integer; const AOldReg, ANewReg: TRegister): Boolean;
  1799. var
  1800. OldSupReg, NewSupReg: TSuperRegister;
  1801. OldSubReg, NewSubReg: TSubRegister;
  1802. OldRegType: TRegisterType;
  1803. ThisOper: POper;
  1804. begin
  1805. ThisOper := p.oper[OperIdx]; { Faster to access overall }
  1806. Result := False;
  1807. if (AOldReg = NR_NO) or (ANewReg = NR_NO) then
  1808. InternalError(2020011801);
  1809. OldSupReg := getsupreg(AOldReg);
  1810. OldSubReg := getsubreg(AOldReg);
  1811. OldRegType := getregtype(AOldReg);
  1812. NewSupReg := getsupreg(ANewReg);
  1813. NewSubReg := getsubreg(ANewReg);
  1814. if OldRegType <> getregtype(ANewReg) then
  1815. InternalError(2020011802);
  1816. if OldSubReg <> NewSubReg then
  1817. InternalError(2020011803);
  1818. case ThisOper^.typ of
  1819. top_reg:
  1820. if (
  1821. (ThisOper^.reg = AOldReg) or
  1822. (
  1823. (OldRegType = R_INTREGISTER) and
  1824. (getsupreg(ThisOper^.reg) = OldSupReg) and
  1825. (getregtype(ThisOper^.reg) = R_INTREGISTER) and
  1826. (
  1827. (getsubreg(ThisOper^.reg) <= OldSubReg)
  1828. {$ifndef x86_64}
  1829. and (
  1830. { Under i386 and i8086, ESI, EDI, EBP and ESP
  1831. don't have an 8-bit representation }
  1832. (getsubreg(ThisOper^.reg) >= R_SUBW) or
  1833. not (NewSupReg in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  1834. )
  1835. {$endif x86_64}
  1836. )
  1837. )
  1838. ) then
  1839. begin
  1840. ThisOper^.reg := newreg(getregtype(ANewReg), NewSupReg, getsubreg(p.oper[OperIdx]^.reg));
  1841. Result := True;
  1842. end;
  1843. top_ref:
  1844. if ReplaceRegisterInRef(ThisOper^.ref^, AOldReg, ANewReg) then
  1845. Result := True;
  1846. else
  1847. ;
  1848. end;
  1849. end;
  1850. { Replaces all references to AOldReg in an instruction to ANewReg }
  1851. function TX86AsmOptimizer.ReplaceRegisterInInstruction(const p: taicpu; const AOldReg, ANewReg: TRegister): Boolean;
  1852. const
  1853. ReadFlag: array[0..3] of TInsChange = (Ch_Rop1, Ch_Rop2, Ch_Rop3, Ch_Rop4);
  1854. var
  1855. OperIdx: Integer;
  1856. begin
  1857. Result := False;
  1858. for OperIdx := 0 to p.ops - 1 do
  1859. if (ReadFlag[OperIdx] in InsProp[p.Opcode].Ch) and
  1860. { The shift and rotate instructions can only use CL }
  1861. not (
  1862. (OperIdx = 0) and
  1863. { This second condition just helps to avoid unnecessarily
  1864. calling MatchInstruction for 10 different opcodes }
  1865. (p.oper[0]^.reg = NR_CL) and
  1866. MatchInstruction(p, [A_RCL, A_RCR, A_ROL, A_ROR, A_SAL, A_SAR, A_SHL, A_SHLD, A_SHR, A_SHRD], [])
  1867. ) then
  1868. Result := ReplaceRegisterInOper(p, OperIdx, AOldReg, ANewReg) or Result;
  1869. end;
  1870. class function TX86AsmOptimizer.IsRefSafe(const ref: PReference): Boolean; inline;
  1871. begin
  1872. Result :=
  1873. (ref^.index = NR_NO) and
  1874. (
  1875. {$ifdef x86_64}
  1876. (
  1877. (ref^.base = NR_RIP) and
  1878. (ref^.refaddr in [addr_pic, addr_pic_no_got])
  1879. ) or
  1880. {$endif x86_64}
  1881. (ref^.base = NR_STACK_POINTER_REG) or
  1882. (ref^.base = current_procinfo.framepointer)
  1883. );
  1884. end;
  1885. function TX86AsmOptimizer.ConvertLEA(const p: taicpu): Boolean;
  1886. var
  1887. l: asizeint;
  1888. begin
  1889. Result := False;
  1890. { Should have been checked previously }
  1891. if p.opcode <> A_LEA then
  1892. InternalError(2020072501);
  1893. { do not mess with the stack point as adjusting it by lea is recommend, except if we optimize for size }
  1894. if (p.oper[1]^.reg=NR_STACK_POINTER_REG) and
  1895. not(cs_opt_size in current_settings.optimizerswitches) then
  1896. exit;
  1897. with p.oper[0]^.ref^ do
  1898. begin
  1899. if (base <> p.oper[1]^.reg) or
  1900. (index <> NR_NO) or
  1901. assigned(symbol) then
  1902. exit;
  1903. l:=offset;
  1904. if (l=1) and UseIncDec then
  1905. begin
  1906. p.opcode:=A_INC;
  1907. p.loadreg(0,p.oper[1]^.reg);
  1908. p.ops:=1;
  1909. DebugMsg(SPeepholeOptimization + 'Lea2Inc done',p);
  1910. end
  1911. else if (l=-1) and UseIncDec then
  1912. begin
  1913. p.opcode:=A_DEC;
  1914. p.loadreg(0,p.oper[1]^.reg);
  1915. p.ops:=1;
  1916. DebugMsg(SPeepholeOptimization + 'Lea2Dec done',p);
  1917. end
  1918. else
  1919. begin
  1920. if (l<0) and (l<>-2147483648) then
  1921. begin
  1922. p.opcode:=A_SUB;
  1923. p.loadConst(0,-l);
  1924. DebugMsg(SPeepholeOptimization + 'Lea2Sub done',p);
  1925. end
  1926. else
  1927. begin
  1928. p.opcode:=A_ADD;
  1929. p.loadConst(0,l);
  1930. DebugMsg(SPeepholeOptimization + 'Lea2Add done',p);
  1931. end;
  1932. end;
  1933. end;
  1934. Result := True;
  1935. end;
  1936. function TX86AsmOptimizer.DeepMOVOpt(const p_mov: taicpu; const hp: taicpu): Boolean;
  1937. var
  1938. CurrentReg, ReplaceReg: TRegister;
  1939. begin
  1940. Result := False;
  1941. ReplaceReg := taicpu(p_mov).oper[0]^.reg;
  1942. CurrentReg := taicpu(p_mov).oper[1]^.reg;
  1943. case hp.opcode of
  1944. A_FSTSW, A_FNSTSW,
  1945. A_IN, A_INS, A_OUT, A_OUTS,
  1946. A_CMPS, A_LODS, A_MOVS, A_SCAS, A_STOS:
  1947. { These routines have explicit operands, but they are restricted in
  1948. what they can be (e.g. IN and OUT can only read from AL, AX or
  1949. EAX. }
  1950. Exit;
  1951. A_IMUL:
  1952. begin
  1953. { The 1-operand version writes to implicit registers
  1954. The 2-operand version reads from the first operator, and reads
  1955. from and writes to the second (equivalent to Ch_ROp1, ChRWOp2).
  1956. the 3-operand version reads from a register that it doesn't write to
  1957. }
  1958. case hp.ops of
  1959. 1:
  1960. if (
  1961. (
  1962. (hp.opsize = S_B) and (getsupreg(CurrentReg) <> RS_EAX)
  1963. ) or
  1964. not (getsupreg(CurrentReg) in [RS_EAX, RS_EDX])
  1965. ) and ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  1966. begin
  1967. Result := True;
  1968. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 1)', hp);
  1969. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1970. end;
  1971. 2:
  1972. { Only modify the first parameter }
  1973. if ReplaceRegisterInOper(hp, 0, CurrentReg, ReplaceReg) then
  1974. begin
  1975. Result := True;
  1976. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 2)', hp);
  1977. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1978. end;
  1979. 3:
  1980. { Only modify the second parameter }
  1981. if ReplaceRegisterInOper(hp, 1, CurrentReg, ReplaceReg) then
  1982. begin
  1983. Result := True;
  1984. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovIMul2MovIMul 3)', hp);
  1985. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1986. end;
  1987. else
  1988. InternalError(2020012901);
  1989. end;
  1990. end;
  1991. else
  1992. if (hp.ops > 0) and
  1993. ReplaceRegisterInInstruction(hp, CurrentReg, ReplaceReg) then
  1994. begin
  1995. Result := True;
  1996. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + debug_regname(ReplaceReg) + '; changed to minimise pipeline stall (MovXXX2MovXXX)', hp);
  1997. AllocRegBetween(ReplaceReg, p_mov, hp, UsedRegs);
  1998. end;
  1999. end;
  2000. end;
  2001. function TX86AsmOptimizer.OptPass1MOV(var p : tai) : boolean;
  2002. var
  2003. hp1, hp2, hp3: tai;
  2004. DoOptimisation, TempBool: Boolean;
  2005. procedure convert_mov_value(signed_movop: tasmop; max_value: tcgint); inline;
  2006. begin
  2007. if taicpu(hp1).opcode = signed_movop then
  2008. begin
  2009. if taicpu(p).oper[0]^.val > max_value shr 1 then
  2010. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val - max_value - 1 { Convert to signed }
  2011. end
  2012. else
  2013. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and max_value; { Trim to unsigned }
  2014. end;
  2015. var
  2016. GetNextInstruction_p, TempRegUsed, CrossJump: Boolean;
  2017. PreMessage, RegName1, RegName2, InputVal, MaskNum: string;
  2018. NewSize: topsize;
  2019. CurrentReg: TRegister;
  2020. begin
  2021. Result:=false;
  2022. GetNextInstruction_p:=GetNextInstruction(p, hp1);
  2023. { remove mov reg1,reg1? }
  2024. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^)
  2025. then
  2026. begin
  2027. DebugMsg(SPeepholeOptimization + 'Mov2Nop 1 done',p);
  2028. { take care of the register (de)allocs following p }
  2029. RemoveCurrentP(p, hp1);
  2030. Result:=true;
  2031. exit;
  2032. end;
  2033. { All the next optimisations require a next instruction }
  2034. if not GetNextInstruction_p or (hp1.typ <> ait_instruction) then
  2035. Exit;
  2036. { Look for:
  2037. mov %reg1,%reg2
  2038. ??? %reg2,r/m
  2039. Change to:
  2040. mov %reg1,%reg2
  2041. ??? %reg1,r/m
  2042. }
  2043. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2044. begin
  2045. CurrentReg := taicpu(p).oper[1]^.reg;
  2046. if RegReadByInstruction(CurrentReg, hp1) and
  2047. DeepMOVOpt(taicpu(p), taicpu(hp1)) then
  2048. begin
  2049. TransferUsedRegs(TmpUsedRegs);
  2050. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2051. if not RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs) and
  2052. { Just in case something didn't get modified (e.g. an
  2053. implicit register) }
  2054. not RegReadByInstruction(CurrentReg, hp1) then
  2055. begin
  2056. { We can remove the original MOV }
  2057. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3 done',p);
  2058. RemoveCurrentp(p, hp1);
  2059. { UsedRegs got updated by RemoveCurrentp }
  2060. Result := True;
  2061. Exit;
  2062. end;
  2063. { If we know a MOV instruction has become a null operation, we might as well
  2064. get rid of it now to save time. }
  2065. if (taicpu(hp1).opcode = A_MOV) and
  2066. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2067. SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[0]^.reg) and
  2068. { Just being a register is enough to confirm it's a null operation }
  2069. (taicpu(hp1).oper[0]^.typ = top_reg) then
  2070. begin
  2071. Result := True;
  2072. { Speed-up to reduce a pipeline stall... if we had something like...
  2073. movl %eax,%edx
  2074. movw %dx,%ax
  2075. ... the second instruction would change to movw %ax,%ax, but
  2076. given that it is now %ax that's active rather than %eax,
  2077. penalties might occur due to a partial register write, so instead,
  2078. change it to a MOVZX instruction when optimising for speed.
  2079. }
  2080. if not (cs_opt_size in current_settings.optimizerswitches) and
  2081. IsMOVZXAcceptable and
  2082. (taicpu(hp1).opsize < taicpu(p).opsize)
  2083. {$ifdef x86_64}
  2084. { operations already implicitly set the upper 64 bits to zero }
  2085. and not ((taicpu(hp1).opsize = S_L) and (taicpu(p).opsize = S_Q))
  2086. {$endif x86_64}
  2087. then
  2088. begin
  2089. CurrentReg := taicpu(hp1).oper[1]^.reg;
  2090. DebugMsg(SPeepholeOptimization + 'Zero-extension to minimise pipeline stall (Mov2Movz)',hp1);
  2091. case taicpu(p).opsize of
  2092. S_W:
  2093. if taicpu(hp1).opsize = S_B then
  2094. taicpu(hp1).opsize := S_BL
  2095. else
  2096. InternalError(2020012911);
  2097. S_L{$ifdef x86_64}, S_Q{$endif x86_64}:
  2098. case taicpu(hp1).opsize of
  2099. S_B:
  2100. taicpu(hp1).opsize := S_BL;
  2101. S_W:
  2102. taicpu(hp1).opsize := S_WL;
  2103. else
  2104. InternalError(2020012912);
  2105. end;
  2106. else
  2107. InternalError(2020012910);
  2108. end;
  2109. taicpu(hp1).opcode := A_MOVZX;
  2110. taicpu(hp1).oper[1]^.reg := newreg(getregtype(CurrentReg), getsupreg(CurrentReg), R_SUBD)
  2111. end
  2112. else
  2113. begin
  2114. GetNextInstruction_p := GetNextInstruction(hp1, hp2);
  2115. DebugMsg(SPeepholeOptimization + 'Mov2Nop 4 done',hp1);
  2116. RemoveInstruction(hp1);
  2117. { The instruction after what was hp1 is now the immediate next instruction,
  2118. so we can continue to make optimisations if it's present }
  2119. if not GetNextInstruction_p or (hp2.typ <> ait_instruction) then
  2120. Exit;
  2121. hp1 := hp2;
  2122. end;
  2123. end;
  2124. end;
  2125. end;
  2126. { Depending on the DeepMOVOpt above, it may turn out that hp1 completely
  2127. overwrites the original destination register. e.g.
  2128. movl ###,%reg2d
  2129. movslq ###,%reg2q (### doesn't have to be the same as the first one)
  2130. In this case, we can remove the MOV (Go to "Mov2Nop 5" below)
  2131. }
  2132. if (taicpu(p).oper[1]^.typ = top_reg) and
  2133. MatchInstruction(hp1, [A_LEA, A_MOV, A_MOVSX, A_MOVZX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}], []) and
  2134. (taicpu(hp1).oper[1]^.typ = top_reg) and
  2135. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2136. begin
  2137. if RegInOp(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[0]^) then
  2138. begin
  2139. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  2140. case taicpu(p).oper[0]^.typ of
  2141. top_const:
  2142. { We have something like:
  2143. movb $x, %regb
  2144. movzbl %regb,%regd
  2145. Change to:
  2146. movl $x, %regd
  2147. }
  2148. begin
  2149. case taicpu(hp1).opsize of
  2150. S_BW:
  2151. begin
  2152. convert_mov_value(A_MOVSX, $FF);
  2153. setsubreg(taicpu(p).oper[1]^.reg, R_SUBW);
  2154. taicpu(p).opsize := S_W;
  2155. end;
  2156. S_BL:
  2157. begin
  2158. convert_mov_value(A_MOVSX, $FF);
  2159. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2160. taicpu(p).opsize := S_L;
  2161. end;
  2162. S_WL:
  2163. begin
  2164. convert_mov_value(A_MOVSX, $FFFF);
  2165. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  2166. taicpu(p).opsize := S_L;
  2167. end;
  2168. {$ifdef x86_64}
  2169. S_BQ:
  2170. begin
  2171. convert_mov_value(A_MOVSX, $FF);
  2172. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2173. taicpu(p).opsize := S_Q;
  2174. end;
  2175. S_WQ:
  2176. begin
  2177. convert_mov_value(A_MOVSX, $FFFF);
  2178. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2179. taicpu(p).opsize := S_Q;
  2180. end;
  2181. S_LQ:
  2182. begin
  2183. convert_mov_value(A_MOVSXD, $FFFFFFFF); { Note it's MOVSXD, not MOVSX }
  2184. setsubreg(taicpu(p).oper[1]^.reg, R_SUBQ);
  2185. taicpu(p).opsize := S_Q;
  2186. end;
  2187. {$endif x86_64}
  2188. else
  2189. { If hp1 was a MOV instruction, it should have been
  2190. optimised already }
  2191. InternalError(2020021001);
  2192. end;
  2193. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 2 done',p);
  2194. RemoveInstruction(hp1);
  2195. Result := True;
  2196. Exit;
  2197. end;
  2198. top_ref:
  2199. { We have something like:
  2200. movb mem, %regb
  2201. movzbl %regb,%regd
  2202. Change to:
  2203. movzbl mem, %regd
  2204. }
  2205. if (taicpu(p).oper[0]^.ref^.refaddr<>addr_full) and (IsMOVZXAcceptable or (taicpu(hp1).opcode<>A_MOVZX)) then
  2206. begin
  2207. DebugMsg(SPeepholeOptimization + 'MovMovXX2MovXX 1 done',p);
  2208. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  2209. RemoveCurrentP(p, hp1);
  2210. Result:=True;
  2211. Exit;
  2212. end;
  2213. else
  2214. if (taicpu(hp1).opcode <> A_MOV) and (taicpu(hp1).opcode <> A_LEA) then
  2215. { Just to make a saving, since there are no more optimisations with MOVZX and MOVSX/D }
  2216. Exit;
  2217. end;
  2218. end
  2219. { The RegInOp check makes sure that movl r/m,%reg1l; movzbl (%reg1l),%reg1l"
  2220. and "movl r/m,%reg1; leal $1(%reg1,%reg2),%reg1" etc. are not incorrectly
  2221. optimised }
  2222. else
  2223. begin
  2224. DebugMsg(SPeepholeOptimization + 'Mov2Nop 5 done',p);
  2225. RemoveCurrentP(p, hp1);
  2226. Result := True;
  2227. Exit;
  2228. end;
  2229. end;
  2230. if (taicpu(hp1).opcode = A_AND) and
  2231. (taicpu(p).oper[1]^.typ = top_reg) and
  2232. MatchOpType(taicpu(hp1),top_const,top_reg) then
  2233. begin
  2234. if MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[1]^) then
  2235. begin
  2236. case taicpu(p).opsize of
  2237. S_L:
  2238. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  2239. begin
  2240. { Optimize out:
  2241. mov x, %reg
  2242. and ffffffffh, %reg
  2243. }
  2244. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 1 done',p);
  2245. RemoveInstruction(hp1);
  2246. Result:=true;
  2247. exit;
  2248. end;
  2249. S_Q: { TODO: Confirm if this is even possible }
  2250. if (taicpu(hp1).oper[0]^.val = $ffffffffffffffff) then
  2251. begin
  2252. { Optimize out:
  2253. mov x, %reg
  2254. and ffffffffffffffffh, %reg
  2255. }
  2256. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 2 done',p);
  2257. RemoveInstruction(hp1);
  2258. Result:=true;
  2259. exit;
  2260. end;
  2261. else
  2262. ;
  2263. end;
  2264. if ((taicpu(p).oper[0]^.typ=top_reg) or
  2265. ((taicpu(p).oper[0]^.typ=top_ref) and (taicpu(p).oper[0]^.ref^.refaddr<>addr_full))) and
  2266. GetNextInstruction(hp1,hp2) and
  2267. MatchInstruction(hp2,A_TEST,[taicpu(p).opsize]) and
  2268. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp2).oper[1]^) and
  2269. (MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^) or
  2270. MatchOperand(taicpu(hp2).oper[0]^,-1)) and
  2271. GetNextInstruction(hp2,hp3) and
  2272. MatchInstruction(hp3,A_Jcc,A_Setcc,[]) and
  2273. (taicpu(hp3).condition in [C_E,C_NE]) then
  2274. begin
  2275. TransferUsedRegs(TmpUsedRegs);
  2276. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2277. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2278. if not(RegUsedAfterInstruction(taicpu(hp2).oper[1]^.reg, hp2, TmpUsedRegs)) then
  2279. begin
  2280. DebugMsg(SPeepholeOptimization + 'MovAndTest2Test done',p);
  2281. taicpu(hp1).loadoper(1,taicpu(p).oper[0]^);
  2282. taicpu(hp1).opcode:=A_TEST;
  2283. RemoveInstruction(hp2);
  2284. RemoveCurrentP(p, hp1);
  2285. Result:=true;
  2286. exit;
  2287. end;
  2288. end;
  2289. end
  2290. else if IsMOVZXAcceptable and
  2291. (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(hp1).oper[1]^.typ = top_reg) and
  2292. (taicpu(p).oper[0]^.typ <> top_const) and { MOVZX only supports registers and memory, not immediates (use MOV for that!) }
  2293. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  2294. then
  2295. begin
  2296. InputVal := debug_operstr(taicpu(p).oper[0]^);
  2297. MaskNum := debug_tostr(taicpu(hp1).oper[0]^.val);
  2298. case taicpu(p).opsize of
  2299. S_B:
  2300. if (taicpu(hp1).oper[0]^.val = $ff) then
  2301. begin
  2302. { Convert:
  2303. movb x, %regl movb x, %regl
  2304. andw ffh, %regw andl ffh, %regd
  2305. To:
  2306. movzbw x, %regd movzbl x, %regd
  2307. (Identical registers, just different sizes)
  2308. }
  2309. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 8-bit register name }
  2310. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 16/32-bit register name }
  2311. case taicpu(hp1).opsize of
  2312. S_W: NewSize := S_BW;
  2313. S_L: NewSize := S_BL;
  2314. {$ifdef x86_64}
  2315. S_Q: NewSize := S_BQ;
  2316. {$endif x86_64}
  2317. else
  2318. InternalError(2018011510);
  2319. end;
  2320. end
  2321. else
  2322. NewSize := S_NO;
  2323. S_W:
  2324. if (taicpu(hp1).oper[0]^.val = $ffff) then
  2325. begin
  2326. { Convert:
  2327. movw x, %regw
  2328. andl ffffh, %regd
  2329. To:
  2330. movzwl x, %regd
  2331. (Identical registers, just different sizes)
  2332. }
  2333. RegName1 := debug_regname(taicpu(p).oper[1]^.reg); { 16-bit register name }
  2334. RegName2 := debug_regname(taicpu(hp1).oper[1]^.reg); { 32-bit register name }
  2335. case taicpu(hp1).opsize of
  2336. S_L: NewSize := S_WL;
  2337. {$ifdef x86_64}
  2338. S_Q: NewSize := S_WQ;
  2339. {$endif x86_64}
  2340. else
  2341. InternalError(2018011511);
  2342. end;
  2343. end
  2344. else
  2345. NewSize := S_NO;
  2346. else
  2347. NewSize := S_NO;
  2348. end;
  2349. if NewSize <> S_NO then
  2350. begin
  2351. PreMessage := 'mov' + debug_opsize2str(taicpu(p).opsize) + ' ' + InputVal + ',' + RegName1;
  2352. { The actual optimization }
  2353. taicpu(p).opcode := A_MOVZX;
  2354. taicpu(p).changeopsize(NewSize);
  2355. taicpu(p).oper[1]^ := taicpu(hp1).oper[1]^;
  2356. { Safeguard if "and" is followed by a conditional command }
  2357. TransferUsedRegs(TmpUsedRegs);
  2358. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  2359. if (RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  2360. begin
  2361. { At this point, the "and" command is effectively equivalent to
  2362. "test %reg,%reg". This will be handled separately by the
  2363. Peephole Optimizer. [Kit] }
  2364. DebugMsg(SPeepholeOptimization + PreMessage +
  2365. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2366. end
  2367. else
  2368. begin
  2369. DebugMsg(SPeepholeOptimization + PreMessage + '; and' + debug_opsize2str(taicpu(hp1).opsize) + ' $' + MaskNum + ',' + RegName2 +
  2370. ' -> movz' + debug_opsize2str(NewSize) + ' ' + InputVal + ',' + RegName2, p);
  2371. RemoveInstruction(hp1);
  2372. end;
  2373. Result := True;
  2374. Exit;
  2375. end;
  2376. end;
  2377. end;
  2378. if (taicpu(hp1).opcode = A_OR) and
  2379. (taicpu(p).oper[1]^.typ = top_reg) and
  2380. MatchOperand(taicpu(p).oper[0]^, 0) and
  2381. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) then
  2382. begin
  2383. { mov 0, %reg
  2384. or ###,%reg
  2385. Change to (only if the flags are not used):
  2386. mov ###,%reg
  2387. }
  2388. TransferUsedRegs(TmpUsedRegs);
  2389. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2390. DoOptimisation := True;
  2391. { Even if the flags are used, we might be able to do the optimisation
  2392. if the conditions are predictable }
  2393. if RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2394. begin
  2395. { Only perform if ### = %reg (the same register) or equal to 0,
  2396. so %reg is guaranteed to still have a value of zero }
  2397. if MatchOperand(taicpu(hp1).oper[0]^, 0) or
  2398. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) then
  2399. begin
  2400. hp2 := hp1;
  2401. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2402. while RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) and
  2403. GetNextInstruction(hp2, hp3) do
  2404. begin
  2405. { Don't continue modifying if the flags state is getting changed }
  2406. if RegModifiedByInstruction(NR_DEFAULTFLAGS, hp3) then
  2407. Break;
  2408. UpdateUsedRegs(TmpUsedRegs, tai(hp3.Next));
  2409. if MatchInstruction(hp3, A_Jcc, A_SETcc, A_CMOVcc, []) then
  2410. begin
  2411. if condition_in(C_E, taicpu(hp3).condition) or (taicpu(hp3).condition in [C_NC, C_NS, C_NO]) then
  2412. begin
  2413. { Condition is always true }
  2414. case taicpu(hp3).opcode of
  2415. A_Jcc:
  2416. begin
  2417. DebugMsg(SPeepholeOptimization + 'Condition is always true (jump made unconditional)', hp3);
  2418. { Check for jump shortcuts before we destroy the condition }
  2419. DoJumpOptimizations(hp3, TempBool);
  2420. MakeUnconditional(taicpu(hp3));
  2421. Result := True;
  2422. end;
  2423. A_CMOVcc:
  2424. begin
  2425. DebugMsg(SPeepholeOptimization + 'Condition is always true (CMOVcc -> MOV)', hp3);
  2426. taicpu(hp3).opcode := A_MOV;
  2427. taicpu(hp3).condition := C_None;
  2428. Result := True;
  2429. end;
  2430. A_SETcc:
  2431. begin
  2432. DebugMsg(SPeepholeOptimization + 'Condition is always true (changed to MOV 1)', hp3);
  2433. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  2434. taicpu(hp3).opcode := A_MOV;
  2435. taicpu(hp3).ops := 2;
  2436. taicpu(hp3).condition := C_None;
  2437. taicpu(hp3).opsize := S_B;
  2438. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2439. taicpu(hp3).loadconst(0, 1);
  2440. Result := True;
  2441. end;
  2442. else
  2443. InternalError(2021090701);
  2444. end;
  2445. end
  2446. 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
  2447. begin
  2448. { Condition is always false }
  2449. case taicpu(hp3).opcode of
  2450. A_Jcc:
  2451. begin
  2452. DebugMsg(SPeepholeOptimization + 'Condition is always false (jump removed)', hp3);
  2453. TAsmLabel(taicpu(hp3).oper[0]^.ref^.symbol).decrefs;
  2454. RemoveInstruction(hp3);
  2455. Result := True;
  2456. { Since hp3 was deleted, hp2 must not be updated }
  2457. Continue;
  2458. end;
  2459. A_CMOVcc:
  2460. begin
  2461. DebugMsg(SPeepholeOptimization + 'Condition is always false (conditional load removed)', hp3);
  2462. RemoveInstruction(hp3);
  2463. Result := True;
  2464. { Since hp3 was deleted, hp2 must not be updated }
  2465. Continue;
  2466. end;
  2467. A_SETcc:
  2468. begin
  2469. DebugMsg(SPeepholeOptimization + 'Condition is always false (changed to MOV 0)', hp3);
  2470. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  2471. taicpu(hp3).opcode := A_MOV;
  2472. taicpu(hp3).ops := 2;
  2473. taicpu(hp3).condition := C_None;
  2474. taicpu(hp3).opsize := S_B;
  2475. taicpu(hp3).loadreg(1,taicpu(hp3).oper[0]^.reg);
  2476. taicpu(hp3).loadconst(0, 0);
  2477. Result := True;
  2478. end;
  2479. else
  2480. InternalError(2021090702);
  2481. end;
  2482. end
  2483. else
  2484. { Uncertain what to do - don't optimise (although optimise other conditional statements if present) }
  2485. DoOptimisation := False;
  2486. end;
  2487. hp2 := hp3;
  2488. end;
  2489. { Flags are still in use - don't optimise }
  2490. if DoOptimisation and RegInUsedRegs(NR_DEFAULTFLAGS, TmpUsedRegs) then
  2491. DoOptimisation := False;
  2492. end
  2493. else
  2494. DoOptimisation := False;
  2495. end;
  2496. if DoOptimisation then
  2497. begin
  2498. {$ifdef x86_64}
  2499. { OR only supports 32-bit sign-extended constants for 64-bit
  2500. instructions, so compensate for this if the constant is
  2501. encoded as a value greater than or equal to 2^31 }
  2502. if (taicpu(hp1).opsize = S_Q) and
  2503. (taicpu(hp1).oper[0]^.typ = top_const) and
  2504. (taicpu(hp1).oper[0]^.val >= $80000000) then
  2505. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val or $FFFFFFFF00000000;
  2506. {$endif x86_64}
  2507. DebugMsg(SPeepholeOptimization + 'MOV 0 / OR -> MOV', p);
  2508. taicpu(hp1).opcode := A_MOV;
  2509. RemoveCurrentP(p, hp1);
  2510. Result := True;
  2511. Exit;
  2512. end;
  2513. end;
  2514. { Next instruction is also a MOV ? }
  2515. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) then
  2516. begin
  2517. if (taicpu(p).oper[1]^.typ = top_reg) and
  2518. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) then
  2519. begin
  2520. CurrentReg := taicpu(p).oper[1]^.reg;
  2521. TransferUsedRegs(TmpUsedRegs);
  2522. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2523. { we have
  2524. mov x, %treg
  2525. mov %treg, y
  2526. }
  2527. if not(RegInOp(CurrentReg, taicpu(hp1).oper[1]^)) then
  2528. if not(RegUsedAfterInstruction(CurrentReg, hp1, TmpUsedRegs)) then
  2529. { we've got
  2530. mov x, %treg
  2531. mov %treg, y
  2532. with %treg is not used after }
  2533. case taicpu(p).oper[0]^.typ Of
  2534. { top_reg is covered by DeepMOVOpt }
  2535. top_const:
  2536. begin
  2537. { change
  2538. mov const, %treg
  2539. mov %treg, y
  2540. to
  2541. mov const, y
  2542. }
  2543. if (taicpu(hp1).oper[1]^.typ=top_reg) or
  2544. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2545. begin
  2546. if taicpu(hp1).oper[1]^.typ=top_reg then
  2547. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2548. taicpu(p).loadOper(1,taicpu(hp1).oper[1]^);
  2549. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 5 done',p);
  2550. RemoveInstruction(hp1);
  2551. Result:=true;
  2552. Exit;
  2553. end;
  2554. end;
  2555. top_ref:
  2556. if (taicpu(hp1).oper[1]^.typ = top_reg) then
  2557. begin
  2558. { change
  2559. mov mem, %treg
  2560. mov %treg, %reg
  2561. to
  2562. mov mem, %reg"
  2563. }
  2564. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2565. taicpu(p).loadreg(1, taicpu(hp1).oper[1]^.reg);
  2566. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 3 done',p);
  2567. RemoveInstruction(hp1);
  2568. Result:=true;
  2569. Exit;
  2570. end;
  2571. else
  2572. ;
  2573. end
  2574. else
  2575. { %treg is used afterwards, but all eventualities
  2576. other than the first MOV instruction being a constant
  2577. are covered by DeepMOVOpt, so only check for that }
  2578. if (taicpu(p).oper[0]^.typ = top_const) and
  2579. (
  2580. { For MOV operations, a size saving is only made if the register/const is byte-sized }
  2581. not (cs_opt_size in current_settings.optimizerswitches) or
  2582. (taicpu(hp1).opsize = S_B)
  2583. ) and
  2584. (
  2585. (taicpu(hp1).oper[1]^.typ = top_reg) or
  2586. ((taicpu(p).oper[0]^.val >= low(longint)) and (taicpu(p).oper[0]^.val <= high(longint)))
  2587. ) then
  2588. begin
  2589. DebugMsg(SPeepholeOptimization + debug_operstr(taicpu(hp1).oper[0]^) + ' = $' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 6b)',hp1);
  2590. taicpu(hp1).loadconst(0, taicpu(p).oper[0]^.val);
  2591. end;
  2592. end;
  2593. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  2594. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  2595. { mov reg1, mem1 or mov mem1, reg1
  2596. mov mem2, reg2 mov reg2, mem2}
  2597. begin
  2598. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  2599. { mov reg1, mem1 or mov mem1, reg1
  2600. mov mem2, reg1 mov reg2, mem1}
  2601. begin
  2602. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2603. { Removes the second statement from
  2604. mov reg1, mem1/reg2
  2605. mov mem1/reg2, reg1 }
  2606. begin
  2607. if taicpu(p).oper[0]^.typ=top_reg then
  2608. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  2609. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 1',p);
  2610. RemoveInstruction(hp1);
  2611. Result:=true;
  2612. exit;
  2613. end
  2614. else
  2615. begin
  2616. TransferUsedRegs(TmpUsedRegs);
  2617. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  2618. if (taicpu(p).oper[1]^.typ = top_ref) and
  2619. { mov reg1, mem1
  2620. mov mem2, reg1 }
  2621. (taicpu(hp1).oper[0]^.ref^.refaddr = addr_no) and
  2622. GetNextInstruction(hp1, hp2) and
  2623. MatchInstruction(hp2,A_CMP,[taicpu(p).opsize]) and
  2624. OpsEqual(taicpu(p).oper[1]^,taicpu(hp2).oper[0]^) and
  2625. OpsEqual(taicpu(p).oper[0]^,taicpu(hp2).oper[1]^) and
  2626. not(RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp2, TmpUsedRegs)) then
  2627. { change to
  2628. mov reg1, mem1 mov reg1, mem1
  2629. mov mem2, reg1 cmp reg1, mem2
  2630. cmp mem1, reg1
  2631. }
  2632. begin
  2633. RemoveInstruction(hp2);
  2634. taicpu(hp1).opcode := A_CMP;
  2635. taicpu(hp1).loadref(1,taicpu(hp1).oper[0]^.ref^);
  2636. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2637. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2638. DebugMsg(SPeepholeOptimization + 'MovMovCmp2MovCmp done',hp1);
  2639. end;
  2640. end;
  2641. end
  2642. else if (taicpu(p).oper[1]^.typ=top_ref) and
  2643. OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  2644. begin
  2645. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,UsedRegs);
  2646. taicpu(hp1).loadreg(0,taicpu(p).oper[0]^.reg);
  2647. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov1 done',p);
  2648. end
  2649. else
  2650. begin
  2651. TransferUsedRegs(TmpUsedRegs);
  2652. if GetNextInstruction(hp1, hp2) and
  2653. MatchOpType(taicpu(p),top_ref,top_reg) and
  2654. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  2655. (taicpu(hp1).oper[1]^.typ = top_ref) and
  2656. MatchInstruction(hp2,A_MOV,[taicpu(p).opsize]) and
  2657. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  2658. RefsEqual(taicpu(hp2).oper[0]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  2659. if not RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^) and
  2660. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,tmpUsedRegs)) then
  2661. { mov mem1, %reg1
  2662. mov %reg1, mem2
  2663. mov mem2, reg2
  2664. to:
  2665. mov mem1, reg2
  2666. mov reg2, mem2}
  2667. begin
  2668. AllocRegBetween(taicpu(hp2).oper[1]^.reg,p,hp2,usedregs);
  2669. DebugMsg(SPeepholeOptimization + 'MovMovMov2MovMov 1 done',p);
  2670. taicpu(p).loadoper(1,taicpu(hp2).oper[1]^);
  2671. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  2672. RemoveInstruction(hp2);
  2673. end
  2674. {$ifdef i386}
  2675. { this is enabled for i386 only, as the rules to create the reg sets below
  2676. are too complicated for x86-64, so this makes this code too error prone
  2677. on x86-64
  2678. }
  2679. else if (taicpu(p).oper[1]^.reg <> taicpu(hp2).oper[1]^.reg) and
  2680. not(RegInRef(taicpu(p).oper[1]^.reg,taicpu(p).oper[0]^.ref^)) and
  2681. not(RegInRef(taicpu(hp2).oper[1]^.reg,taicpu(hp2).oper[0]^.ref^)) then
  2682. { mov mem1, reg1 mov mem1, reg1
  2683. mov reg1, mem2 mov reg1, mem2
  2684. mov mem2, reg2 mov mem2, reg1
  2685. to: to:
  2686. mov mem1, reg1 mov mem1, reg1
  2687. mov mem1, reg2 mov reg1, mem2
  2688. mov reg1, mem2
  2689. or (if mem1 depends on reg1
  2690. and/or if mem2 depends on reg2)
  2691. to:
  2692. mov mem1, reg1
  2693. mov reg1, mem2
  2694. mov reg1, reg2
  2695. }
  2696. begin
  2697. taicpu(hp1).loadRef(0,taicpu(p).oper[0]^.ref^);
  2698. taicpu(hp1).loadReg(1,taicpu(hp2).oper[1]^.reg);
  2699. taicpu(hp2).loadRef(1,taicpu(hp2).oper[0]^.ref^);
  2700. taicpu(hp2).loadReg(0,taicpu(p).oper[1]^.reg);
  2701. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2702. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  2703. (getsupreg(taicpu(p).oper[0]^.ref^.base) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2704. AllocRegBetween(taicpu(p).oper[0]^.ref^.base,p,hp2,usedregs);
  2705. if (taicpu(p).oper[0]^.ref^.index <> NR_NO) and
  2706. (getsupreg(taicpu(p).oper[0]^.ref^.index) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX,RS_ESI,RS_EDI]) then
  2707. AllocRegBetween(taicpu(p).oper[0]^.ref^.index,p,hp2,usedregs);
  2708. end
  2709. else if (taicpu(hp1).Oper[0]^.reg <> taicpu(hp2).Oper[1]^.reg) then
  2710. begin
  2711. taicpu(hp2).loadReg(0,taicpu(hp1).Oper[0]^.reg);
  2712. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp2,usedregs);
  2713. end
  2714. else
  2715. begin
  2716. RemoveInstruction(hp2);
  2717. end
  2718. {$endif i386}
  2719. ;
  2720. end;
  2721. end
  2722. { movl [mem1],reg1
  2723. movl [mem1],reg2
  2724. to
  2725. movl [mem1],reg1
  2726. movl reg1,reg2
  2727. }
  2728. else if MatchOpType(taicpu(p),top_ref,top_reg) and
  2729. MatchOpType(taicpu(hp1),top_ref,top_reg) and
  2730. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2731. RefsEqual(taicpu(p).oper[0]^.ref^,taicpu(hp1).oper[0]^.ref^) and
  2732. (taicpu(p).oper[0]^.ref^.volatility=[]) and
  2733. (taicpu(hp1).oper[0]^.ref^.volatility=[]) and
  2734. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.base)) and
  2735. not(SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^.index)) then
  2736. begin
  2737. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 2',p);
  2738. taicpu(hp1).loadReg(0,taicpu(p).oper[1]^.reg);
  2739. end;
  2740. { movl const1,[mem1]
  2741. movl [mem1],reg1
  2742. to
  2743. movl const1,reg1
  2744. movl reg1,[mem1]
  2745. }
  2746. if MatchOpType(Taicpu(p),top_const,top_ref) and
  2747. MatchOpType(Taicpu(hp1),top_ref,top_reg) and
  2748. (taicpu(p).opsize = taicpu(hp1).opsize) and
  2749. RefsEqual(taicpu(hp1).oper[0]^.ref^,taicpu(p).oper[1]^.ref^) and
  2750. not(RegInRef(taicpu(hp1).oper[1]^.reg,taicpu(hp1).oper[0]^.ref^)) then
  2751. begin
  2752. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,usedregs);
  2753. taicpu(hp1).loadReg(0,taicpu(hp1).oper[1]^.reg);
  2754. taicpu(hp1).loadRef(1,taicpu(p).oper[1]^.ref^);
  2755. taicpu(p).loadReg(1,taicpu(hp1).oper[0]^.reg);
  2756. taicpu(hp1).fileinfo := taicpu(p).fileinfo;
  2757. DebugMsg(SPeepholeOptimization + 'MovMov2MovMov 1',p);
  2758. Result:=true;
  2759. exit;
  2760. end;
  2761. { mov x,reg1; mov y,reg1 -> mov y,reg1 is handled by the Mov2Nop 5 optimisation }
  2762. end;
  2763. { search further than the next instruction for a mov }
  2764. if
  2765. { check as much as possible before the expensive GetNextInstructionUsingRegCond call }
  2766. (taicpu(p).oper[1]^.typ = top_reg) and
  2767. (taicpu(p).oper[0]^.typ in [top_reg,top_const]) and
  2768. not RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp1) then
  2769. begin
  2770. { we work with hp2 here, so hp1 can be still used later on when
  2771. checking for GetNextInstruction_p }
  2772. hp3 := hp1;
  2773. { Initialise CrossJump (if it becomes True at any point, it will remain True) }
  2774. CrossJump := False;
  2775. while GetNextInstructionUsingRegCond(hp3,hp2,taicpu(p).oper[1]^.reg,CrossJump) and
  2776. { GetNextInstructionUsingRegCond only searches one instruction ahead unless -O3 is specified }
  2777. (hp2.typ=ait_instruction) do
  2778. begin
  2779. case taicpu(hp2).opcode of
  2780. A_MOV:
  2781. if MatchOperand(taicpu(hp2).oper[0]^,taicpu(p).oper[1]^.reg) and
  2782. ((taicpu(p).oper[0]^.typ=top_const) or
  2783. ((taicpu(p).oper[0]^.typ=top_reg) and
  2784. not(RegModifiedBetween(taicpu(p).oper[0]^.reg, p, hp2))
  2785. )
  2786. ) then
  2787. begin
  2788. { we have
  2789. mov x, %treg
  2790. mov %treg, y
  2791. }
  2792. TransferUsedRegs(TmpUsedRegs);
  2793. TmpUsedRegs[R_INTREGISTER].Update(tai(p.Next));
  2794. { We don't need to call UpdateUsedRegs for every instruction between
  2795. p and hp2 because the register we're concerned about will not
  2796. become deallocated (otherwise GetNextInstructionUsingReg would
  2797. have stopped at an earlier instruction). [Kit] }
  2798. TempRegUsed :=
  2799. CrossJump { Assume the register is in use if it crossed a conditional jump } or
  2800. RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) or
  2801. RegReadByInstruction(taicpu(p).oper[1]^.reg, hp1);
  2802. case taicpu(p).oper[0]^.typ Of
  2803. top_reg:
  2804. begin
  2805. { change
  2806. mov %reg, %treg
  2807. mov %treg, y
  2808. to
  2809. mov %reg, y
  2810. }
  2811. CurrentReg := taicpu(p).oper[0]^.reg; { Saves on a handful of pointer dereferences }
  2812. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  2813. if taicpu(hp2).oper[1]^.reg = CurrentReg then
  2814. begin
  2815. { %reg = y - remove hp2 completely (doing it here instead of relying on
  2816. the "mov %reg,%reg" optimisation might cut down on a pass iteration) }
  2817. if TempRegUsed then
  2818. begin
  2819. DebugMsg(SPeepholeOptimization + debug_regname(CurrentReg) + ' = ' + RegName1 + '; removed unnecessary instruction (MovMov2MovNop 6b}',hp2);
  2820. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  2821. { Set the start of the next GetNextInstructionUsingRegCond search
  2822. to start at the entry right before hp2 (which is about to be removed) }
  2823. hp3 := tai(hp2.Previous);
  2824. RemoveInstruction(hp2);
  2825. { See if there's more we can optimise }
  2826. Continue;
  2827. end
  2828. else
  2829. begin
  2830. RemoveInstruction(hp2);
  2831. { We can remove the original MOV too }
  2832. DebugMsg(SPeepholeOptimization + 'MovMov2NopNop 6b done',p);
  2833. RemoveCurrentP(p, hp1);
  2834. Result:=true;
  2835. Exit;
  2836. end;
  2837. end
  2838. else
  2839. begin
  2840. AllocRegBetween(CurrentReg, p, hp2, UsedRegs);
  2841. taicpu(hp2).loadReg(0, CurrentReg);
  2842. if TempRegUsed then
  2843. begin
  2844. { Don't remove the first instruction if the temporary register is in use }
  2845. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_regname(CurrentReg) + '; changed to minimise pipeline stall (MovMov2Mov 6a}',hp2);
  2846. { No need to set Result to True. If there's another instruction later on
  2847. that can be optimised, it will be detected when the main Pass 1 loop
  2848. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  2849. end
  2850. else
  2851. begin
  2852. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 6 done',p);
  2853. RemoveCurrentP(p, hp1);
  2854. Result:=true;
  2855. Exit;
  2856. end;
  2857. end;
  2858. end;
  2859. top_const:
  2860. if not (cs_opt_size in current_settings.optimizerswitches) or (taicpu(hp2).opsize = S_B) then
  2861. begin
  2862. { change
  2863. mov const, %treg
  2864. mov %treg, y
  2865. to
  2866. mov const, y
  2867. }
  2868. if (taicpu(hp2).oper[1]^.typ=top_reg) or
  2869. ((taicpu(p).oper[0]^.val>=low(longint)) and (taicpu(p).oper[0]^.val<=high(longint))) then
  2870. begin
  2871. RegName1 := debug_regname(taicpu(hp2).oper[0]^.reg);
  2872. taicpu(hp2).loadOper(0,taicpu(p).oper[0]^);
  2873. if TempRegUsed then
  2874. begin
  2875. { Don't remove the first instruction if the temporary register is in use }
  2876. DebugMsg(SPeepholeOptimization + RegName1 + ' = ' + debug_tostr(taicpu(p).oper[0]^.val) + '; changed to minimise pipeline stall (MovMov2Mov 7a)',hp2);
  2877. { No need to set Result to True. If there's another instruction later on
  2878. that can be optimised, it will be detected when the main Pass 1 loop
  2879. reaches what is now hp2 and passes it through OptPass1MOV. [Kit] };
  2880. end
  2881. else
  2882. begin
  2883. DebugMsg(SPeepholeOptimization + 'MovMov2Mov 7 done',p);
  2884. RemoveCurrentP(p, hp1);
  2885. Result:=true;
  2886. Exit;
  2887. end;
  2888. end;
  2889. end;
  2890. else
  2891. Internalerror(2019103001);
  2892. end;
  2893. end;
  2894. A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  2895. if MatchOpType(taicpu(hp2), top_reg, top_reg) and
  2896. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  2897. SuperRegistersEqual(taicpu(hp2).oper[1]^.reg, taicpu(p).oper[1]^.reg) then
  2898. begin
  2899. {
  2900. Change from:
  2901. mov ###, %reg
  2902. ...
  2903. movs/z %reg,%reg (Same register, just different sizes)
  2904. To:
  2905. movs/z ###, %reg (Longer version)
  2906. ...
  2907. (remove)
  2908. }
  2909. DebugMsg(SPeepholeOptimization + 'MovMovs/z2Mov/s/z done', p);
  2910. taicpu(p).oper[1]^.reg := taicpu(hp2).oper[1]^.reg;
  2911. { Keep the first instruction as mov if ### is a constant }
  2912. if taicpu(p).oper[0]^.typ = top_const then
  2913. taicpu(p).opsize := reg2opsize(taicpu(hp2).oper[1]^.reg)
  2914. else
  2915. begin
  2916. taicpu(p).opcode := taicpu(hp2).opcode;
  2917. taicpu(p).opsize := taicpu(hp2).opsize;
  2918. end;
  2919. DebugMsg(SPeepholeOptimization + 'Removed movs/z instruction and extended earlier write (MovMovs/z2Mov/s/z)', hp2);
  2920. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp2, UsedRegs);
  2921. RemoveInstruction(hp2);
  2922. Result := True;
  2923. Exit;
  2924. end;
  2925. else
  2926. if MatchOpType(taicpu(p), top_reg, top_reg) then
  2927. begin
  2928. CurrentReg := taicpu(p).oper[1]^.reg;
  2929. TransferUsedRegs(TmpUsedRegs);
  2930. TmpUsedRegs[R_INTREGISTER].Update(tai(p.Next));
  2931. if
  2932. not RegModifiedByInstruction(taicpu(p).oper[0]^.reg, hp1) and
  2933. not RegModifiedBetween(taicpu(p).oper[0]^.reg, hp1, hp2) and
  2934. DeepMovOpt(taicpu(p), taicpu(hp2)) then
  2935. begin
  2936. { Just in case something didn't get modified (e.g. an
  2937. implicit register) }
  2938. if not RegReadByInstruction(CurrentReg, hp2) and
  2939. { If a conditional jump was crossed, do not delete
  2940. the original MOV no matter what }
  2941. not CrossJump then
  2942. begin
  2943. TransferUsedRegs(TmpUsedRegs);
  2944. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  2945. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  2946. if
  2947. { Make sure the original register isn't still present
  2948. and has been written to (e.g. with SHRX) }
  2949. RegLoadedWithNewValue(CurrentReg, hp2) or
  2950. not RegUsedAfterInstruction(CurrentReg, hp2, TmpUsedRegs) then
  2951. begin
  2952. { We can remove the original MOV }
  2953. DebugMsg(SPeepholeOptimization + 'Mov2Nop 3b done',p);
  2954. RemoveCurrentp(p, hp1);
  2955. Result := True;
  2956. Exit;
  2957. end
  2958. else
  2959. begin
  2960. { See if there's more we can optimise }
  2961. hp3 := hp2;
  2962. Continue;
  2963. end;
  2964. end;
  2965. end;
  2966. end;
  2967. end;
  2968. { Break out of the while loop under normal circumstances }
  2969. Break;
  2970. end;
  2971. end;
  2972. if (aoc_MovAnd2Mov_3 in OptsToCheck) and
  2973. (taicpu(p).oper[1]^.typ = top_reg) and
  2974. (taicpu(p).opsize = S_L) and
  2975. GetNextInstructionUsingRegTrackingUse(p,hp2,taicpu(p).oper[1]^.reg) and
  2976. (taicpu(hp2).opcode = A_AND) and
  2977. (MatchOpType(taicpu(hp2),top_const,top_reg) or
  2978. (MatchOpType(taicpu(hp2),top_reg,top_reg) and
  2979. MatchOperand(taicpu(hp2).oper[0]^,taicpu(hp2).oper[1]^))
  2980. ) then
  2981. begin
  2982. if SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp2).oper[1]^.reg) then
  2983. begin
  2984. if ((taicpu(hp2).oper[0]^.typ=top_const) and (taicpu(hp2).oper[0]^.val = $ffffffff)) or
  2985. ((taicpu(hp2).oper[0]^.typ=top_reg) and (taicpu(hp2).opsize=S_L)) then
  2986. begin
  2987. { Optimize out:
  2988. mov x, %reg
  2989. and ffffffffh, %reg
  2990. }
  2991. DebugMsg(SPeepholeOptimization + 'MovAnd2Mov 3 done',p);
  2992. RemoveInstruction(hp2);
  2993. Result:=true;
  2994. exit;
  2995. end;
  2996. end;
  2997. end;
  2998. { leave out the mov from "mov reg, x(%frame_pointer); leave/ret" (with
  2999. x >= RetOffset) as it doesn't do anything (it writes either to a
  3000. parameter or to the temporary storage room for the function
  3001. result)
  3002. }
  3003. if IsExitCode(hp1) and
  3004. (taicpu(p).oper[1]^.typ = top_ref) and
  3005. (taicpu(p).oper[1]^.ref^.index = NR_NO) and
  3006. (
  3007. (
  3008. (taicpu(p).oper[1]^.ref^.base = current_procinfo.FramePointer) and
  3009. not (
  3010. assigned(current_procinfo.procdef.funcretsym) and
  3011. (taicpu(p).oper[1]^.ref^.offset <= tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)
  3012. )
  3013. ) or
  3014. { Also discard writes to the stack that are below the base pointer,
  3015. as this is temporary storage rather than a function result on the
  3016. stack, say. }
  3017. (
  3018. (taicpu(p).oper[1]^.ref^.base = NR_STACK_POINTER_REG) and
  3019. (taicpu(p).oper[1]^.ref^.offset < current_procinfo.final_localsize)
  3020. )
  3021. ) then
  3022. begin
  3023. RemoveCurrentp(p, hp1);
  3024. DebugMsg(SPeepholeOptimization + 'removed deadstore before leave/ret',p);
  3025. RemoveLastDeallocForFuncRes(p);
  3026. Result:=true;
  3027. exit;
  3028. end;
  3029. if MatchInstruction(hp1,A_CMP,A_TEST,[taicpu(p).opsize]) then
  3030. begin
  3031. if MatchOpType(taicpu(p),top_reg,top_ref) and
  3032. (taicpu(hp1).oper[1]^.typ = top_ref) and
  3033. RefsEqual(taicpu(p).oper[1]^.ref^, taicpu(hp1).oper[1]^.ref^) then
  3034. begin
  3035. { change
  3036. mov reg1, mem1
  3037. test/cmp x, mem1
  3038. to
  3039. mov reg1, mem1
  3040. test/cmp x, reg1
  3041. }
  3042. taicpu(hp1).loadreg(1,taicpu(p).oper[0]^.reg);
  3043. DebugMsg(SPeepholeOptimization + 'MovTestCmp2MovTestCmp 1',hp1);
  3044. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3045. Result := True;
  3046. Exit;
  3047. end;
  3048. if MatchOpType(taicpu(p),top_ref,top_reg) and
  3049. { The x86 assemblers have difficulty comparing values against absolute addresses }
  3050. (taicpu(p).oper[0]^.ref^.refaddr in [addr_no, addr_pic, addr_pic_no_got]) and
  3051. (taicpu(hp1).oper[0]^.typ <> top_ref) and
  3052. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  3053. (
  3054. (
  3055. (taicpu(hp1).opcode = A_TEST)
  3056. ) or (
  3057. (taicpu(hp1).opcode = A_CMP) and
  3058. { A sanity check more than anything }
  3059. not MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg)
  3060. )
  3061. ) then
  3062. begin
  3063. { change
  3064. mov mem, %reg
  3065. cmp/test x, %reg / test %reg,%reg
  3066. (reg deallocated)
  3067. to
  3068. cmp/test x, mem / cmp 0, mem
  3069. }
  3070. TransferUsedRegs(TmpUsedRegs);
  3071. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  3072. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) then
  3073. begin
  3074. { Convert test %reg,%reg or test $-1,%reg to cmp $0,mem }
  3075. if (taicpu(hp1).opcode = A_TEST) and
  3076. (
  3077. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) or
  3078. MatchOperand(taicpu(hp1).oper[0]^, -1)
  3079. ) then
  3080. begin
  3081. taicpu(hp1).opcode := A_CMP;
  3082. taicpu(hp1).loadconst(0, 0);
  3083. end;
  3084. taicpu(hp1).loadref(1, taicpu(p).oper[0]^.ref^);
  3085. DebugMsg(SPeepholeOptimization + 'MOV/CMP -> CMP (memory check)', p);
  3086. RemoveCurrentP(p, hp1);
  3087. Result := True;
  3088. Exit;
  3089. end;
  3090. end;
  3091. end;
  3092. if MatchInstruction(hp1,A_LEA,[S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  3093. { If the flags register is in use, don't change the instruction to an
  3094. ADD otherwise this will scramble the flags. [Kit] }
  3095. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) then
  3096. begin
  3097. if MatchOpType(Taicpu(p),top_ref,top_reg) and
  3098. ((MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(hp1).oper[1]^.reg,Taicpu(p).oper[1]^.reg) and
  3099. (Taicpu(hp1).oper[0]^.ref^.base<>Taicpu(p).oper[1]^.reg)
  3100. ) or
  3101. (MatchReference(Taicpu(hp1).oper[0]^.ref^,Taicpu(p).oper[1]^.reg,Taicpu(hp1).oper[1]^.reg) and
  3102. (Taicpu(hp1).oper[0]^.ref^.index<>Taicpu(p).oper[1]^.reg)
  3103. )
  3104. ) then
  3105. { mov reg1,ref
  3106. lea reg2,[reg1,reg2]
  3107. to
  3108. add reg2,ref}
  3109. begin
  3110. TransferUsedRegs(TmpUsedRegs);
  3111. { reg1 may not be used afterwards }
  3112. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  3113. begin
  3114. Taicpu(hp1).opcode:=A_ADD;
  3115. Taicpu(hp1).oper[0]^.ref^:=Taicpu(p).oper[0]^.ref^;
  3116. DebugMsg(SPeepholeOptimization + 'MovLea2Add done',hp1);
  3117. RemoveCurrentp(p, hp1);
  3118. result:=true;
  3119. exit;
  3120. end;
  3121. end;
  3122. { If the LEA instruction can be converted into an arithmetic instruction,
  3123. it may be possible to then fold it in the next optimisation, otherwise
  3124. there's nothing more that can be optimised here. }
  3125. if not ConvertLEA(taicpu(hp1)) then
  3126. Exit;
  3127. end;
  3128. if (taicpu(p).oper[1]^.typ = top_reg) and
  3129. (hp1.typ = ait_instruction) and
  3130. GetNextInstruction(hp1, hp2) and
  3131. MatchInstruction(hp2,A_MOV,[]) and
  3132. (SuperRegistersEqual(taicpu(hp2).oper[0]^.reg,taicpu(p).oper[1]^.reg)) and
  3133. (topsize2memsize[taicpu(hp1).opsize]>=topsize2memsize[taicpu(hp2).opsize]) and
  3134. (
  3135. IsFoldableArithOp(taicpu(hp1), taicpu(p).oper[1]^.reg)
  3136. {$ifdef x86_64}
  3137. or
  3138. (
  3139. (taicpu(p).opsize=S_L) and (taicpu(hp1).opsize=S_Q) and (taicpu(hp2).opsize=S_L) and
  3140. IsFoldableArithOp(taicpu(hp1), newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[1]^.reg),R_SUBQ))
  3141. )
  3142. {$endif x86_64}
  3143. ) then
  3144. begin
  3145. if OpsEqual(taicpu(hp2).oper[1]^, taicpu(p).oper[0]^) and
  3146. (taicpu(hp2).oper[0]^.typ=top_reg) then
  3147. { change movsX/movzX reg/ref, reg2
  3148. add/sub/or/... reg3/$const, reg2
  3149. mov reg2 reg/ref
  3150. dealloc reg2
  3151. to
  3152. add/sub/or/... reg3/$const, reg/ref }
  3153. begin
  3154. TransferUsedRegs(TmpUsedRegs);
  3155. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3156. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3157. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3158. begin
  3159. { by example:
  3160. movswl %si,%eax movswl %si,%eax p
  3161. decl %eax addl %edx,%eax hp1
  3162. movw %ax,%si movw %ax,%si hp2
  3163. ->
  3164. movswl %si,%eax movswl %si,%eax p
  3165. decw %eax addw %edx,%eax hp1
  3166. movw %ax,%si movw %ax,%si hp2
  3167. }
  3168. DebugMsg(SPeepholeOptimization + 'MovOpMov2Op ('+
  3169. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3170. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3171. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3172. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3173. {
  3174. ->
  3175. movswl %si,%eax movswl %si,%eax p
  3176. decw %si addw %dx,%si hp1
  3177. movw %ax,%si movw %ax,%si hp2
  3178. }
  3179. case taicpu(hp1).ops of
  3180. 1:
  3181. begin
  3182. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3183. if taicpu(hp1).oper[0]^.typ=top_reg then
  3184. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3185. end;
  3186. 2:
  3187. begin
  3188. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3189. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3190. (taicpu(hp1).opcode<>A_SHL) and
  3191. (taicpu(hp1).opcode<>A_SHR) and
  3192. (taicpu(hp1).opcode<>A_SAR) then
  3193. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3194. end;
  3195. else
  3196. internalerror(2008042701);
  3197. end;
  3198. {
  3199. ->
  3200. decw %si addw %dx,%si p
  3201. }
  3202. RemoveInstruction(hp2);
  3203. RemoveCurrentP(p, hp1);
  3204. Result:=True;
  3205. Exit;
  3206. end;
  3207. end;
  3208. if MatchOpType(taicpu(hp2),top_reg,top_reg) and
  3209. not(SuperRegistersEqual(taicpu(hp1).oper[0]^.reg,taicpu(hp2).oper[1]^.reg)) and
  3210. ((topsize2memsize[taicpu(hp1).opsize]<= topsize2memsize[taicpu(hp2).opsize]) or
  3211. { opsize matters for these opcodes, we could probably work around this, but it is not worth the effort }
  3212. ((taicpu(hp1).opcode<>A_SHL) and (taicpu(hp1).opcode<>A_SHR) and (taicpu(hp1).opcode<>A_SAR))
  3213. )
  3214. {$ifdef i386}
  3215. { byte registers of esi, edi, ebp, esp are not available on i386 }
  3216. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3217. and ((taicpu(hp2).opsize<>S_B) or not(getsupreg(taicpu(p).oper[0]^.reg) in [RS_ESI,RS_EDI,RS_EBP,RS_ESP]))
  3218. {$endif i386}
  3219. then
  3220. { change movsX/movzX reg/ref, reg2
  3221. add/sub/or/... regX/$const, reg2
  3222. mov reg2, reg3
  3223. dealloc reg2
  3224. to
  3225. movsX/movzX reg/ref, reg3
  3226. add/sub/or/... reg3/$const, reg3
  3227. }
  3228. begin
  3229. TransferUsedRegs(TmpUsedRegs);
  3230. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3231. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  3232. If not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp2,TmpUsedRegs)) then
  3233. begin
  3234. { by example:
  3235. movswl %si,%eax movswl %si,%eax p
  3236. decl %eax addl %edx,%eax hp1
  3237. movw %ax,%si movw %ax,%si hp2
  3238. ->
  3239. movswl %si,%eax movswl %si,%eax p
  3240. decw %eax addw %edx,%eax hp1
  3241. movw %ax,%si movw %ax,%si hp2
  3242. }
  3243. DebugMsg(SPeepholeOptimization + 'MovOpMov2MovOp ('+
  3244. debug_op2str(taicpu(p).opcode)+debug_opsize2str(taicpu(p).opsize)+' '+
  3245. debug_op2str(taicpu(hp1).opcode)+debug_opsize2str(taicpu(hp1).opsize)+' '+
  3246. debug_op2str(taicpu(hp2).opcode)+debug_opsize2str(taicpu(hp2).opsize)+')',p);
  3247. { limit size of constants as well to avoid assembler errors, but
  3248. check opsize to avoid overflow when left shifting the 1 }
  3249. if (taicpu(p).oper[0]^.typ=top_const) and (topsize2memsize[taicpu(hp2).opsize]<=63) then
  3250. taicpu(p).oper[0]^.val:=taicpu(p).oper[0]^.val and ((qword(1) shl topsize2memsize[taicpu(hp2).opsize])-1);
  3251. {$ifdef x86_64}
  3252. { Be careful of, for example:
  3253. movl %reg1,%reg2
  3254. addl %reg3,%reg2
  3255. movq %reg2,%reg4
  3256. This will cause problems if the upper 32-bits of %reg3 or %reg4 are non-zero
  3257. }
  3258. if (taicpu(hp1).opsize = S_L) and (taicpu(hp2).opsize = S_Q) then
  3259. begin
  3260. taicpu(hp2).changeopsize(S_L);
  3261. setsubreg(taicpu(hp2).oper[0]^.reg, R_SUBD);
  3262. setsubreg(taicpu(hp2).oper[1]^.reg, R_SUBD);
  3263. end;
  3264. {$endif x86_64}
  3265. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  3266. taicpu(p).changeopsize(taicpu(hp2).opsize);
  3267. if taicpu(p).oper[0]^.typ=top_reg then
  3268. setsubreg(taicpu(p).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3269. taicpu(p).loadoper(1, taicpu(hp2).oper[1]^);
  3270. AllocRegBetween(taicpu(p).oper[1]^.reg,p,hp1,usedregs);
  3271. {
  3272. ->
  3273. movswl %si,%eax movswl %si,%eax p
  3274. decw %si addw %dx,%si hp1
  3275. movw %ax,%si movw %ax,%si hp2
  3276. }
  3277. case taicpu(hp1).ops of
  3278. 1:
  3279. begin
  3280. taicpu(hp1).loadoper(0, taicpu(hp2).oper[1]^);
  3281. if taicpu(hp1).oper[0]^.typ=top_reg then
  3282. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3283. end;
  3284. 2:
  3285. begin
  3286. taicpu(hp1).loadoper(1, taicpu(hp2).oper[1]^);
  3287. if (taicpu(hp1).oper[0]^.typ=top_reg) and
  3288. (taicpu(hp1).opcode<>A_SHL) and
  3289. (taicpu(hp1).opcode<>A_SHR) and
  3290. (taicpu(hp1).opcode<>A_SAR) then
  3291. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  3292. end;
  3293. else
  3294. internalerror(2018111801);
  3295. end;
  3296. {
  3297. ->
  3298. decw %si addw %dx,%si p
  3299. }
  3300. RemoveInstruction(hp2);
  3301. end;
  3302. end;
  3303. end;
  3304. if MatchInstruction(hp1,A_BTS,A_BTR,[Taicpu(p).opsize]) and
  3305. GetNextInstruction(hp1, hp2) and
  3306. MatchInstruction(hp2,A_OR,[Taicpu(p).opsize]) and
  3307. MatchOperand(Taicpu(p).oper[0]^,0) and
  3308. (Taicpu(p).oper[1]^.typ = top_reg) and
  3309. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp1).oper[1]^) and
  3310. MatchOperand(Taicpu(p).oper[1]^,Taicpu(hp2).oper[1]^) then
  3311. { mov reg1,0
  3312. bts reg1,operand1 --> mov reg1,operand2
  3313. or reg1,operand2 bts reg1,operand1}
  3314. begin
  3315. Taicpu(hp2).opcode:=A_MOV;
  3316. asml.remove(hp1);
  3317. insertllitem(hp2,hp2.next,hp1);
  3318. RemoveCurrentp(p, hp1);
  3319. Result:=true;
  3320. exit;
  3321. end;
  3322. {$ifdef x86_64}
  3323. { Convert:
  3324. movq x(ref),%reg64
  3325. shrq y,%reg64
  3326. To:
  3327. movq x+4(ref),%reg32
  3328. shrq y-32,%reg32 (Remove if y = 32)
  3329. }
  3330. if (taicpu(p).opsize = S_Q) and
  3331. (taicpu(p).oper[0]^.typ = top_ref) and { Second operand will be a register }
  3332. (taicpu(p).oper[0]^.ref^.offset <= $7FFFFFFB) and
  3333. MatchInstruction(hp1, A_SHR, [taicpu(p).opsize]) and
  3334. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3335. (taicpu(hp1).oper[0]^.val >= 32) and
  3336. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  3337. begin
  3338. RegName1 := debug_regname(taicpu(hp1).oper[1]^.reg);
  3339. PreMessage := 'movq ' + debug_operstr(taicpu(p).oper[0]^) + ',' + RegName1 + '; ' +
  3340. 'shrq $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + RegName1 + ' -> movl ';
  3341. { Convert to 32-bit }
  3342. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  3343. taicpu(p).opsize := S_L;
  3344. Inc(taicpu(p).oper[0]^.ref^.offset, 4);
  3345. PreMessage := PreMessage + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg);
  3346. if (taicpu(hp1).oper[0]^.val = 32) then
  3347. begin
  3348. DebugMsg(SPeepholeOptimization + PreMessage + ' (MovShr2Mov)', p);
  3349. RemoveInstruction(hp1);
  3350. end
  3351. else
  3352. begin
  3353. { This will potentially open up more arithmetic operations since
  3354. the peephole optimizer now has a big hint that only the lower
  3355. 32 bits are currently in use (and opcodes are smaller in size) }
  3356. setsubreg(taicpu(hp1).oper[1]^.reg, R_SUBD);
  3357. taicpu(hp1).opsize := S_L;
  3358. Dec(taicpu(hp1).oper[0]^.val, 32);
  3359. DebugMsg(SPeepholeOptimization + PreMessage +
  3360. '; shrl $' + debug_tostr(taicpu(hp1).oper[0]^.val) + ',' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' (MovShr2MovShr)', p);
  3361. end;
  3362. Result := True;
  3363. Exit;
  3364. end;
  3365. {$endif x86_64}
  3366. end;
  3367. function TX86AsmOptimizer.OptPass1MOVXX(var p : tai) : boolean;
  3368. var
  3369. hp1 : tai;
  3370. begin
  3371. Result:=false;
  3372. if taicpu(p).ops <> 2 then
  3373. exit;
  3374. if GetNextInstruction(p,hp1) and
  3375. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  3376. (taicpu(hp1).ops = 2) then
  3377. begin
  3378. if (taicpu(hp1).oper[0]^.typ = taicpu(p).oper[1]^.typ) and
  3379. (taicpu(hp1).oper[1]^.typ = taicpu(p).oper[0]^.typ) then
  3380. { movXX reg1, mem1 or movXX mem1, reg1
  3381. movXX mem2, reg2 movXX reg2, mem2}
  3382. begin
  3383. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[0]^) then
  3384. { movXX reg1, mem1 or movXX mem1, reg1
  3385. movXX mem2, reg1 movXX reg2, mem1}
  3386. begin
  3387. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3388. begin
  3389. { Removes the second statement from
  3390. movXX reg1, mem1/reg2
  3391. movXX mem1/reg2, reg1
  3392. }
  3393. if taicpu(p).oper[0]^.typ=top_reg then
  3394. AllocRegBetween(taicpu(p).oper[0]^.reg,p,hp1,usedregs);
  3395. { Removes the second statement from
  3396. movXX mem1/reg1, reg2
  3397. movXX reg2, mem1/reg1
  3398. }
  3399. if (taicpu(p).oper[1]^.typ=top_reg) and
  3400. not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,UsedRegs)) then
  3401. begin
  3402. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2Nop 1 done',p);
  3403. RemoveInstruction(hp1);
  3404. RemoveCurrentp(p); { p will now be equal to the instruction that follows what was hp1 }
  3405. end
  3406. else
  3407. begin
  3408. DebugMsg(SPeepholeOptimization + 'MovXXMovXX2MoVXX 1 done',p);
  3409. RemoveInstruction(hp1);
  3410. end;
  3411. Result:=true;
  3412. exit;
  3413. end
  3414. end;
  3415. end;
  3416. end;
  3417. end;
  3418. function TX86AsmOptimizer.OptPass1OP(var p : tai) : boolean;
  3419. var
  3420. hp1 : tai;
  3421. begin
  3422. result:=false;
  3423. { replace
  3424. <Op>X %mreg1,%mreg2 // Op in [ADD,MUL]
  3425. MovX %mreg2,%mreg1
  3426. dealloc %mreg2
  3427. by
  3428. <Op>X %mreg2,%mreg1
  3429. ?
  3430. }
  3431. if GetNextInstruction(p,hp1) and
  3432. { we mix single and double opperations here because we assume that the compiler
  3433. generates vmovapd only after double operations and vmovaps only after single operations }
  3434. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  3435. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3436. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[1]^) and
  3437. (taicpu(p).oper[0]^.typ=top_reg) then
  3438. begin
  3439. TransferUsedRegs(TmpUsedRegs);
  3440. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3441. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3442. begin
  3443. taicpu(p).loadoper(0,taicpu(hp1).oper[0]^);
  3444. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3445. DebugMsg(SPeepholeOptimization + 'OpMov2Op done',p);
  3446. RemoveInstruction(hp1);
  3447. result:=true;
  3448. end;
  3449. end;
  3450. end;
  3451. function TX86AsmOptimizer.OptPass1Test(var p: tai) : boolean;
  3452. var
  3453. hp1, p_label, p_dist, hp1_dist: tai;
  3454. JumpLabel, JumpLabel_dist: TAsmLabel;
  3455. begin
  3456. Result := False;
  3457. if (taicpu(p).oper[1]^.typ = top_reg) then
  3458. begin
  3459. if GetNextInstruction(p, hp1) and
  3460. MatchInstruction(hp1,A_MOV,[]) and
  3461. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  3462. (
  3463. (taicpu(p).oper[0]^.typ <> top_reg) or
  3464. not RegInInstruction(taicpu(p).oper[0]^.reg, hp1)
  3465. ) then
  3466. begin
  3467. { If we have something like:
  3468. test %reg1,%reg1
  3469. mov 0,%reg2
  3470. And no registers are shared (the two %reg1's can be different, as
  3471. long as neither of them are also %reg2), move the MOV command to
  3472. before the comparison as this means it can be optimised without
  3473. worrying about the FLAGS register. (This combination is generated
  3474. by "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  3475. }
  3476. SwapMovCmp(p, hp1);
  3477. Result := True;
  3478. Exit;
  3479. end;
  3480. { Search for:
  3481. test %reg,%reg
  3482. j(c1) @lbl1
  3483. ...
  3484. @lbl:
  3485. test %reg,%reg (same register)
  3486. j(c2) @lbl2
  3487. If c2 is a subset of c1, change to:
  3488. test %reg,%reg
  3489. j(c1) @lbl2
  3490. (@lbl1 may become a dead label as a result)
  3491. }
  3492. if (taicpu(p).oper[0]^.typ = top_reg) and
  3493. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  3494. MatchInstruction(hp1, A_JCC, []) and
  3495. IsJumpToLabel(taicpu(hp1)) then
  3496. begin
  3497. JumpLabel := TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol);
  3498. p_label := nil;
  3499. if Assigned(JumpLabel) then
  3500. p_label := getlabelwithsym(JumpLabel);
  3501. if Assigned(p_label) and
  3502. GetNextInstruction(p_label, p_dist) and
  3503. MatchInstruction(p_dist, A_TEST, []) and
  3504. { It's fine if the second test uses smaller sub-registers }
  3505. (taicpu(p_dist).opsize <= taicpu(p).opsize) and
  3506. MatchOpType(taicpu(p_dist), top_reg, top_reg) and
  3507. SuperRegistersEqual(taicpu(p_dist).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  3508. SuperRegistersEqual(taicpu(p_dist).oper[1]^.reg, taicpu(p).oper[1]^.reg) and
  3509. GetNextInstruction(p_dist, hp1_dist) and
  3510. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  3511. begin
  3512. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  3513. if JumpLabel = JumpLabel_dist then
  3514. { This is an infinite loop }
  3515. Exit;
  3516. { Best optimisation when the first condition is a subset (or equal) of the second }
  3517. if condition_in(taicpu(hp1).condition, taicpu(hp1_dist).condition) then
  3518. begin
  3519. { Any registers used here will already be allocated }
  3520. if Assigned(JumpLabel_dist) then
  3521. JumpLabel_dist.IncRefs;
  3522. if Assigned(JumpLabel) then
  3523. JumpLabel.DecRefs;
  3524. DebugMsg(SPeepholeOptimization + 'TEST/Jcc/@Lbl/TEST/Jcc -> TEST/Jcc, redirecting first jump', hp1);
  3525. taicpu(hp1).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  3526. Result := True;
  3527. Exit;
  3528. end;
  3529. end;
  3530. end;
  3531. end;
  3532. end;
  3533. function TX86AsmOptimizer.OptPass1Add(var p : tai) : boolean;
  3534. var
  3535. hp1 : tai;
  3536. begin
  3537. result:=false;
  3538. { replace
  3539. addX const,%reg1
  3540. leaX (%reg1,%reg1,Y),%reg2 // Base or index might not be equal to reg1
  3541. dealloc %reg1
  3542. by
  3543. leaX const+const*Y(%reg1,%reg1,Y),%reg2
  3544. }
  3545. if MatchOpType(taicpu(p),top_const,top_reg) and
  3546. GetNextInstruction(p,hp1) and
  3547. MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  3548. ((taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.base) or
  3549. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index)) then
  3550. begin
  3551. TransferUsedRegs(TmpUsedRegs);
  3552. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3553. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3554. begin
  3555. DebugMsg(SPeepholeOptimization + 'AddLea2Lea done',p);
  3556. if taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.base then
  3557. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val);
  3558. if taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index then
  3559. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.val*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  3560. RemoveCurrentP(p);
  3561. result:=true;
  3562. end;
  3563. end;
  3564. end;
  3565. function TX86AsmOptimizer.OptPass1LEA(var p : tai) : boolean;
  3566. var
  3567. hp1: tai;
  3568. ref: Integer;
  3569. saveref: treference;
  3570. TempReg: TRegister;
  3571. Multiple: TCGInt;
  3572. begin
  3573. Result:=false;
  3574. { removes seg register prefixes from LEA operations, as they
  3575. don't do anything}
  3576. taicpu(p).oper[0]^.ref^.Segment:=NR_NO;
  3577. { changes "lea (%reg1), %reg2" into "mov %reg1, %reg2" }
  3578. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3579. (taicpu(p).oper[0]^.ref^.index = NR_NO) and
  3580. (
  3581. { do not mess with leas accessing the stack pointer
  3582. unless it's a null operation }
  3583. (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) or
  3584. (
  3585. (taicpu(p).oper[0]^.ref^.base = NR_STACK_POINTER_REG) and
  3586. (taicpu(p).oper[0]^.ref^.offset = 0)
  3587. )
  3588. ) and
  3589. (not(Assigned(taicpu(p).oper[0]^.ref^.Symbol))) then
  3590. begin
  3591. if (taicpu(p).oper[0]^.ref^.offset = 0) then
  3592. begin
  3593. if (taicpu(p).oper[0]^.ref^.base <> taicpu(p).oper[1]^.reg) then
  3594. begin
  3595. hp1:=taicpu.op_reg_reg(A_MOV,taicpu(p).opsize,taicpu(p).oper[0]^.ref^.base,
  3596. taicpu(p).oper[1]^.reg);
  3597. InsertLLItem(p.previous,p.next, hp1);
  3598. DebugMsg(SPeepholeOptimization + 'Lea2Mov done',hp1);
  3599. p.free;
  3600. p:=hp1;
  3601. end
  3602. else
  3603. begin
  3604. DebugMsg(SPeepholeOptimization + 'Lea2Nop done',p);
  3605. RemoveCurrentP(p);
  3606. end;
  3607. Result:=true;
  3608. exit;
  3609. end
  3610. else if (
  3611. { continue to use lea to adjust the stack pointer,
  3612. it is the recommended way, but only if not optimizing for size }
  3613. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) or
  3614. (cs_opt_size in current_settings.optimizerswitches)
  3615. ) and
  3616. { If the flags register is in use, don't change the instruction
  3617. to an ADD otherwise this will scramble the flags. [Kit] }
  3618. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  3619. ConvertLEA(taicpu(p)) then
  3620. begin
  3621. Result:=true;
  3622. exit;
  3623. end;
  3624. end;
  3625. if GetNextInstruction(p,hp1) and
  3626. (hp1.typ=ait_instruction) then
  3627. begin
  3628. if MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  3629. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  3630. MatchOpType(Taicpu(hp1),top_reg,top_reg) and
  3631. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) then
  3632. begin
  3633. TransferUsedRegs(TmpUsedRegs);
  3634. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3635. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3636. begin
  3637. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  3638. DebugMsg(SPeepholeOptimization + 'LeaMov2Lea done',p);
  3639. RemoveInstruction(hp1);
  3640. result:=true;
  3641. exit;
  3642. end;
  3643. end;
  3644. { changes
  3645. lea <ref1>, reg1
  3646. <op> ...,<ref. with reg1>,...
  3647. to
  3648. <op> ...,<ref1>,... }
  3649. if (taicpu(p).oper[1]^.reg<>current_procinfo.framepointer) and
  3650. (taicpu(p).oper[1]^.reg<>NR_STACK_POINTER_REG) and
  3651. not(MatchInstruction(hp1,A_LEA,[])) then
  3652. begin
  3653. { find a reference which uses reg1 }
  3654. 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
  3655. ref:=0
  3656. 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
  3657. ref:=1
  3658. else
  3659. ref:=-1;
  3660. if (ref<>-1) and
  3661. { reg1 must be either the base or the index }
  3662. ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) xor (taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg)) then
  3663. begin
  3664. { reg1 can be removed from the reference }
  3665. saveref:=taicpu(hp1).oper[ref]^.ref^;
  3666. if taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg then
  3667. taicpu(hp1).oper[ref]^.ref^.base:=NR_NO
  3668. else if taicpu(hp1).oper[ref]^.ref^.index=taicpu(p).oper[1]^.reg then
  3669. taicpu(hp1).oper[ref]^.ref^.index:=NR_NO
  3670. else
  3671. Internalerror(2019111201);
  3672. { check if the can insert all data of the lea into the second instruction }
  3673. if ((taicpu(hp1).oper[ref]^.ref^.base=taicpu(p).oper[1]^.reg) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  3674. ((taicpu(p).oper[0]^.ref^.base=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.base=NR_NO)) and
  3675. ((taicpu(p).oper[0]^.ref^.index=NR_NO) or (taicpu(hp1).oper[ref]^.ref^.index=NR_NO)) and
  3676. ((taicpu(p).oper[0]^.ref^.symbol=nil) or (taicpu(hp1).oper[ref]^.ref^.symbol=nil)) and
  3677. ((taicpu(p).oper[0]^.ref^.relsymbol=nil) or (taicpu(hp1).oper[ref]^.ref^.relsymbol=nil)) and
  3678. ((taicpu(p).oper[0]^.ref^.scalefactor <= 1) or (taicpu(hp1).oper[ref]^.ref^.scalefactor <= 1)) and
  3679. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.segment=NR_NO)
  3680. {$ifdef x86_64}
  3681. and (abs(taicpu(hp1).oper[ref]^.ref^.offset+taicpu(p).oper[0]^.ref^.offset)<=$7fffffff)
  3682. and (((taicpu(p).oper[0]^.ref^.base<>NR_RIP) and (taicpu(p).oper[0]^.ref^.index<>NR_RIP)) or
  3683. ((taicpu(hp1).oper[ref]^.ref^.base=NR_NO) and (taicpu(hp1).oper[ref]^.ref^.index=NR_NO))
  3684. )
  3685. {$endif x86_64}
  3686. then
  3687. begin
  3688. { reg1 might not used by the second instruction after it is remove from the reference }
  3689. if not(RegInInstruction(taicpu(p).oper[1]^.reg,taicpu(hp1))) then
  3690. begin
  3691. TransferUsedRegs(TmpUsedRegs);
  3692. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  3693. { reg1 is not updated so it might not be used afterwards }
  3694. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  3695. begin
  3696. DebugMsg(SPeepholeOptimization + 'LeaOp2Op done',p);
  3697. if taicpu(p).oper[0]^.ref^.base<>NR_NO then
  3698. taicpu(hp1).oper[ref]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3699. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  3700. taicpu(hp1).oper[ref]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  3701. if taicpu(p).oper[0]^.ref^.symbol<>nil then
  3702. taicpu(hp1).oper[ref]^.ref^.symbol:=taicpu(p).oper[0]^.ref^.symbol;
  3703. if taicpu(p).oper[0]^.ref^.relsymbol<>nil then
  3704. taicpu(hp1).oper[ref]^.ref^.relsymbol:=taicpu(p).oper[0]^.ref^.relsymbol;
  3705. if taicpu(p).oper[0]^.ref^.scalefactor > 1 then
  3706. taicpu(hp1).oper[ref]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  3707. inc(taicpu(hp1).oper[ref]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3708. RemoveCurrentP(p, hp1);
  3709. result:=true;
  3710. exit;
  3711. end
  3712. end;
  3713. end;
  3714. { recover }
  3715. taicpu(hp1).oper[ref]^.ref^:=saveref;
  3716. end;
  3717. end;
  3718. end;
  3719. { for now, we do not mess with the stack pointer, thought it might be usefull to remove
  3720. unneeded lea sequences on the stack pointer, it needs to be tested in detail }
  3721. if (taicpu(p).oper[1]^.reg <> NR_STACK_POINTER_REG) and
  3722. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[1]^.reg) then
  3723. begin
  3724. { Check common LEA/LEA conditions }
  3725. if MatchInstruction(hp1,A_LEA,[taicpu(p).opsize]) and
  3726. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  3727. (taicpu(p).oper[0]^.ref^.relsymbol = nil) and
  3728. (taicpu(p).oper[0]^.ref^.segment = NR_NO) and
  3729. (taicpu(p).oper[0]^.ref^.symbol = nil) and
  3730. (taicpu(hp1).oper[0]^.ref^.relsymbol = nil) and
  3731. (taicpu(hp1).oper[0]^.ref^.segment = NR_NO) and
  3732. (taicpu(hp1).oper[0]^.ref^.symbol = nil) and
  3733. (
  3734. (taicpu(p).oper[0]^.ref^.base = NR_NO) or { Don't call RegModifiedBetween unnecessarily }
  3735. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.base,p,hp1))
  3736. ) and (
  3737. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) or { Don't call RegModifiedBetween unnecessarily }
  3738. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3739. not(RegModifiedBetween(taicpu(p).oper[0]^.ref^.index,p,hp1))
  3740. ) then
  3741. begin
  3742. { changes
  3743. lea (regX,scale), reg1
  3744. lea offset(reg1,reg1), reg1
  3745. to
  3746. lea offset(regX,scale*2), reg1
  3747. and
  3748. lea (regX,scale1), reg1
  3749. lea offset(reg1,scale2), reg1
  3750. to
  3751. lea offset(regX,scale1*scale2), reg1
  3752. ... so long as the final scale does not exceed 8
  3753. (Similarly, allow the first instruction to be "lea (regX,regX),reg1")
  3754. }
  3755. if (taicpu(p).oper[0]^.ref^.offset = 0) and
  3756. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  3757. (
  3758. (
  3759. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  3760. ) or (
  3761. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  3762. (
  3763. (taicpu(p).oper[0]^.ref^.base = taicpu(p).oper[0]^.ref^.index) and
  3764. not(RegUsedBetween(taicpu(p).oper[0]^.ref^.index, p, hp1))
  3765. )
  3766. )
  3767. ) and (
  3768. (
  3769. { lea (reg1,scale2), reg1 variant }
  3770. (taicpu(hp1).oper[0]^.ref^.base = NR_NO) and
  3771. (
  3772. (
  3773. (taicpu(p).oper[0]^.ref^.base = NR_NO) and
  3774. (taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor <= 8)
  3775. ) or (
  3776. { lea (regX,regX), reg1 variant }
  3777. (taicpu(p).oper[0]^.ref^.base <> NR_NO) and
  3778. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 4)
  3779. )
  3780. )
  3781. ) or (
  3782. { lea (reg1,reg1), reg1 variant }
  3783. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  3784. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1)
  3785. )
  3786. ) then
  3787. begin
  3788. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 2 done',p);
  3789. { Make everything homogeneous to make calculations easier }
  3790. if (taicpu(p).oper[0]^.ref^.base <> NR_NO) then
  3791. begin
  3792. if taicpu(p).oper[0]^.ref^.index <> NR_NO then
  3793. { Convert lea (regX,regX),reg1 to lea (regX,2),reg1 }
  3794. taicpu(p).oper[0]^.ref^.scalefactor := 2
  3795. else
  3796. taicpu(p).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.base;
  3797. taicpu(p).oper[0]^.ref^.base := NR_NO;
  3798. end;
  3799. if (taicpu(hp1).oper[0]^.ref^.base = NR_NO) then
  3800. begin
  3801. { Just to prevent miscalculations }
  3802. if (taicpu(hp1).oper[0]^.ref^.scalefactor = 0) then
  3803. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor
  3804. else
  3805. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(hp1).oper[0]^.ref^.scalefactor * taicpu(p).oper[0]^.ref^.scalefactor;
  3806. end
  3807. else
  3808. begin
  3809. taicpu(hp1).oper[0]^.ref^.base := NR_NO;
  3810. taicpu(hp1).oper[0]^.ref^.scalefactor := taicpu(p).oper[0]^.ref^.scalefactor * 2;
  3811. end;
  3812. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.ref^.index;
  3813. RemoveCurrentP(p);
  3814. result:=true;
  3815. exit;
  3816. end
  3817. { changes
  3818. lea offset1(regX), reg1
  3819. lea offset2(reg1), reg1
  3820. to
  3821. lea offset1+offset2(regX), reg1 }
  3822. else if
  3823. (
  3824. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  3825. (taicpu(p).oper[0]^.ref^.index = NR_NO)
  3826. ) or (
  3827. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  3828. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  3829. (
  3830. (
  3831. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3832. (taicpu(p).oper[0]^.ref^.base = NR_NO)
  3833. ) or (
  3834. (taicpu(p).oper[0]^.ref^.scalefactor <= 1) and
  3835. (
  3836. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3837. (
  3838. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  3839. (
  3840. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) or
  3841. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  3842. )
  3843. )
  3844. )
  3845. )
  3846. )
  3847. ) then
  3848. begin
  3849. DebugMsg(SPeepholeOptimization + 'LeaLea2Lea 1 done',p);
  3850. if taicpu(hp1).oper[0]^.ref^.index=taicpu(p).oper[1]^.reg then
  3851. begin
  3852. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.base;
  3853. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset*max(taicpu(hp1).oper[0]^.ref^.scalefactor,1));
  3854. { if the register is used as index and base, we have to increase for base as well
  3855. and adapt base }
  3856. if taicpu(hp1).oper[0]^.ref^.base=taicpu(p).oper[1]^.reg then
  3857. begin
  3858. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3859. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3860. end;
  3861. end
  3862. else
  3863. begin
  3864. inc(taicpu(hp1).oper[0]^.ref^.offset,taicpu(p).oper[0]^.ref^.offset);
  3865. taicpu(hp1).oper[0]^.ref^.base:=taicpu(p).oper[0]^.ref^.base;
  3866. end;
  3867. if taicpu(p).oper[0]^.ref^.index<>NR_NO then
  3868. begin
  3869. taicpu(hp1).oper[0]^.ref^.base:=taicpu(hp1).oper[0]^.ref^.index;
  3870. taicpu(hp1).oper[0]^.ref^.index:=taicpu(p).oper[0]^.ref^.index;
  3871. taicpu(hp1).oper[0]^.ref^.scalefactor:=taicpu(p).oper[0]^.ref^.scalefactor;
  3872. end;
  3873. RemoveCurrentP(p);
  3874. result:=true;
  3875. exit;
  3876. end;
  3877. end;
  3878. { Change:
  3879. leal/q $x(%reg1),%reg2
  3880. ...
  3881. shll/q $y,%reg2
  3882. To:
  3883. leal/q $(x+2^y)(%reg1,2^y),%reg2 (if y <= 3)
  3884. }
  3885. if MatchInstruction(hp1, A_SHL, [taicpu(p).opsize]) and
  3886. MatchOpType(taicpu(hp1), top_const, top_reg) and
  3887. (taicpu(hp1).oper[0]^.val <= 3) then
  3888. begin
  3889. Multiple := 1 shl taicpu(hp1).oper[0]^.val;
  3890. TransferUsedRegs(TmpUsedRegs);
  3891. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  3892. TempReg := taicpu(hp1).oper[1]^.reg; { Store locally to reduce the number of dereferences }
  3893. if
  3894. { This allows the optimisation in some circumstances even if the lea instruction already has a scale factor
  3895. (this works even if scalefactor is zero) }
  3896. ((Multiple * taicpu(p).oper[0]^.ref^.scalefactor) <= 8) and
  3897. { Ensure offset doesn't go out of bounds }
  3898. (abs(taicpu(p).oper[0]^.ref^.offset * Multiple) <= $7FFFFFFF) and
  3899. not (RegInUsedRegs(NR_DEFAULTFLAGS,TmpUsedRegs)) and
  3900. MatchOperand(taicpu(p).oper[1]^, TempReg) and
  3901. (
  3902. (
  3903. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.base, TempReg) and
  3904. (
  3905. (taicpu(p).oper[0]^.ref^.index = NR_NO) or
  3906. (taicpu(p).oper[0]^.ref^.index = NR_INVALID) or
  3907. (
  3908. { Check for lea $x(%reg1,%reg1),%reg2 and treat as it it were lea $x(%reg1,2),%reg2 }
  3909. (taicpu(p).oper[0]^.ref^.index = taicpu(p).oper[0]^.ref^.base) and
  3910. (taicpu(p).oper[0]^.ref^.scalefactor <= 1)
  3911. )
  3912. )
  3913. ) or (
  3914. (
  3915. (taicpu(p).oper[0]^.ref^.base = NR_NO) or
  3916. (taicpu(p).oper[0]^.ref^.base = NR_INVALID)
  3917. ) and
  3918. not SuperRegistersEqual(taicpu(p).oper[0]^.ref^.index, TempReg)
  3919. )
  3920. ) then
  3921. begin
  3922. repeat
  3923. with taicpu(p).oper[0]^.ref^ do
  3924. begin
  3925. { Convert lea $x(%reg1,%reg1),%reg2 to lea $x(%reg1,2),%reg2 }
  3926. if index = base then
  3927. begin
  3928. if Multiple > 4 then
  3929. { Optimisation will no longer work because resultant
  3930. scale factor will exceed 8 }
  3931. Break;
  3932. base := NR_NO;
  3933. scalefactor := 2;
  3934. DebugMsg(SPeepholeOptimization + 'lea $x(%reg1,%reg1),%reg2 -> lea $x(%reg1,2),%reg2 for following optimisation', p);
  3935. end
  3936. else if (base <> NR_NO) and (base <> NR_INVALID) then
  3937. begin
  3938. { Scale factor only works on the index register }
  3939. index := base;
  3940. base := NR_NO;
  3941. end;
  3942. { For safety }
  3943. if scalefactor <= 1 then
  3944. begin
  3945. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 1', p);
  3946. scalefactor := Multiple;
  3947. end
  3948. else
  3949. begin
  3950. DebugMsg(SPeepholeOptimization + 'LeaShl2Lea 2', p);
  3951. scalefactor := scalefactor * Multiple;
  3952. end;
  3953. offset := offset * Multiple;
  3954. end;
  3955. RemoveInstruction(hp1);
  3956. Result := True;
  3957. Exit;
  3958. { This repeat..until loop exists for the benefit of Break }
  3959. until True;
  3960. end;
  3961. end;
  3962. end;
  3963. end;
  3964. function TX86AsmOptimizer.DoSubAddOpt(var p: tai): Boolean;
  3965. var
  3966. hp1 : tai;
  3967. begin
  3968. DoSubAddOpt := False;
  3969. if GetLastInstruction(p, hp1) and
  3970. (hp1.typ = ait_instruction) and
  3971. (taicpu(hp1).opsize = taicpu(p).opsize) then
  3972. case taicpu(hp1).opcode Of
  3973. A_DEC:
  3974. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  3975. MatchOperand(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) then
  3976. begin
  3977. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+1);
  3978. RemoveInstruction(hp1);
  3979. end;
  3980. A_SUB:
  3981. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  3982. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  3983. begin
  3984. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val+taicpu(hp1).oper[0]^.val);
  3985. RemoveInstruction(hp1);
  3986. end;
  3987. A_ADD:
  3988. begin
  3989. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  3990. MatchOperand(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) then
  3991. begin
  3992. taicpu(p).loadConst(0,taicpu(p).oper[0]^.val-taicpu(hp1).oper[0]^.val);
  3993. RemoveInstruction(hp1);
  3994. if (taicpu(p).oper[0]^.val = 0) then
  3995. begin
  3996. hp1 := tai(p.next);
  3997. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  3998. if not GetLastInstruction(hp1, p) then
  3999. p := hp1;
  4000. DoSubAddOpt := True;
  4001. end
  4002. end;
  4003. end;
  4004. else
  4005. ;
  4006. end;
  4007. end;
  4008. function TX86AsmOptimizer.OptPass1Sub(var p : tai) : boolean;
  4009. {$ifdef i386}
  4010. var
  4011. hp1 : tai;
  4012. {$endif i386}
  4013. begin
  4014. Result:=false;
  4015. { * change "subl $2, %esp; pushw x" to "pushl x"}
  4016. { * change "sub/add const1, reg" or "dec reg" followed by
  4017. "sub const2, reg" to one "sub ..., reg" }
  4018. if MatchOpType(taicpu(p),top_const,top_reg) then
  4019. begin
  4020. {$ifdef i386}
  4021. if (taicpu(p).oper[0]^.val = 2) and
  4022. (taicpu(p).oper[1]^.reg = NR_ESP) and
  4023. { Don't do the sub/push optimization if the sub }
  4024. { comes from setting up the stack frame (JM) }
  4025. (not(GetLastInstruction(p,hp1)) or
  4026. not(MatchInstruction(hp1,A_MOV,[S_L]) and
  4027. MatchOperand(taicpu(hp1).oper[0]^,NR_ESP) and
  4028. MatchOperand(taicpu(hp1).oper[0]^,NR_EBP))) then
  4029. begin
  4030. hp1 := tai(p.next);
  4031. while Assigned(hp1) and
  4032. (tai(hp1).typ in [ait_instruction]+SkipInstr) and
  4033. not RegReadByInstruction(NR_ESP,hp1) and
  4034. not RegModifiedByInstruction(NR_ESP,hp1) do
  4035. hp1 := tai(hp1.next);
  4036. if Assigned(hp1) and
  4037. MatchInstruction(hp1,A_PUSH,[S_W]) then
  4038. begin
  4039. taicpu(hp1).changeopsize(S_L);
  4040. if taicpu(hp1).oper[0]^.typ=top_reg then
  4041. setsubreg(taicpu(hp1).oper[0]^.reg,R_SUBWHOLE);
  4042. hp1 := tai(p.next);
  4043. RemoveCurrentp(p, hp1);
  4044. Result:=true;
  4045. exit;
  4046. end;
  4047. end;
  4048. {$endif i386}
  4049. if DoSubAddOpt(p) then
  4050. Result:=true;
  4051. end;
  4052. end;
  4053. function TX86AsmOptimizer.OptPass1SHLSAL(var p : tai) : boolean;
  4054. var
  4055. TmpBool1,TmpBool2 : Boolean;
  4056. tmpref : treference;
  4057. hp1,hp2: tai;
  4058. mask: tcgint;
  4059. begin
  4060. Result:=false;
  4061. { All these optimisations work on "shl/sal const,%reg" }
  4062. if not MatchOpType(taicpu(p),top_const,top_reg) then
  4063. Exit;
  4064. if (taicpu(p).opsize in [S_L{$ifdef x86_64},S_Q{$endif x86_64}]) and
  4065. (taicpu(p).oper[0]^.val <= 3) then
  4066. { Changes "shl const, %reg32; add const/reg, %reg32" to one lea statement }
  4067. begin
  4068. { should we check the next instruction? }
  4069. TmpBool1 := True;
  4070. { have we found an add/sub which could be
  4071. integrated in the lea? }
  4072. TmpBool2 := False;
  4073. reference_reset(tmpref,2,[]);
  4074. TmpRef.index := taicpu(p).oper[1]^.reg;
  4075. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  4076. while TmpBool1 and
  4077. GetNextInstruction(p, hp1) and
  4078. (tai(hp1).typ = ait_instruction) and
  4079. ((((taicpu(hp1).opcode = A_ADD) or
  4080. (taicpu(hp1).opcode = A_SUB)) and
  4081. (taicpu(hp1).oper[1]^.typ = Top_Reg) and
  4082. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)) or
  4083. (((taicpu(hp1).opcode = A_INC) or
  4084. (taicpu(hp1).opcode = A_DEC)) and
  4085. (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  4086. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg)) or
  4087. ((taicpu(hp1).opcode = A_LEA) and
  4088. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  4089. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg))) and
  4090. (not GetNextInstruction(hp1,hp2) or
  4091. not instrReadsFlags(hp2)) Do
  4092. begin
  4093. TmpBool1 := False;
  4094. if taicpu(hp1).opcode=A_LEA then
  4095. begin
  4096. if (TmpRef.base = NR_NO) and
  4097. (taicpu(hp1).oper[0]^.ref^.symbol=nil) and
  4098. (taicpu(hp1).oper[0]^.ref^.relsymbol=nil) and
  4099. (taicpu(hp1).oper[0]^.ref^.segment=NR_NO) and
  4100. ((taicpu(hp1).oper[0]^.ref^.scalefactor=0) or
  4101. (taicpu(hp1).oper[0]^.ref^.scalefactor*tmpref.scalefactor<=8)) then
  4102. begin
  4103. TmpBool1 := True;
  4104. TmpBool2 := True;
  4105. inc(TmpRef.offset, taicpu(hp1).oper[0]^.ref^.offset);
  4106. if taicpu(hp1).oper[0]^.ref^.scalefactor<>0 then
  4107. tmpref.scalefactor:=tmpref.scalefactor*taicpu(hp1).oper[0]^.ref^.scalefactor;
  4108. TmpRef.base := taicpu(hp1).oper[0]^.ref^.base;
  4109. RemoveInstruction(hp1);
  4110. end
  4111. end
  4112. else if (taicpu(hp1).oper[0]^.typ = Top_Const) then
  4113. begin
  4114. TmpBool1 := True;
  4115. TmpBool2 := True;
  4116. case taicpu(hp1).opcode of
  4117. A_ADD:
  4118. inc(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  4119. A_SUB:
  4120. dec(TmpRef.offset, longint(taicpu(hp1).oper[0]^.val));
  4121. else
  4122. internalerror(2019050536);
  4123. end;
  4124. RemoveInstruction(hp1);
  4125. end
  4126. else
  4127. if (taicpu(hp1).oper[0]^.typ = Top_Reg) and
  4128. (((taicpu(hp1).opcode = A_ADD) and
  4129. (TmpRef.base = NR_NO)) or
  4130. (taicpu(hp1).opcode = A_INC) or
  4131. (taicpu(hp1).opcode = A_DEC)) then
  4132. begin
  4133. TmpBool1 := True;
  4134. TmpBool2 := True;
  4135. case taicpu(hp1).opcode of
  4136. A_ADD:
  4137. TmpRef.base := taicpu(hp1).oper[0]^.reg;
  4138. A_INC:
  4139. inc(TmpRef.offset);
  4140. A_DEC:
  4141. dec(TmpRef.offset);
  4142. else
  4143. internalerror(2019050535);
  4144. end;
  4145. RemoveInstruction(hp1);
  4146. end;
  4147. end;
  4148. if TmpBool2
  4149. {$ifndef x86_64}
  4150. or
  4151. ((current_settings.optimizecputype < cpu_Pentium2) and
  4152. (taicpu(p).oper[0]^.val <= 3) and
  4153. not(cs_opt_size in current_settings.optimizerswitches))
  4154. {$endif x86_64}
  4155. then
  4156. begin
  4157. if not(TmpBool2) and
  4158. (taicpu(p).oper[0]^.val=1) then
  4159. begin
  4160. hp1:=taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  4161. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg)
  4162. end
  4163. else
  4164. hp1:=taicpu.op_ref_reg(A_LEA, taicpu(p).opsize, TmpRef,
  4165. taicpu(p).oper[1]^.reg);
  4166. DebugMsg(SPeepholeOptimization + 'ShlAddLeaSubIncDec2Lea',p);
  4167. InsertLLItem(p.previous, p.next, hp1);
  4168. p.free;
  4169. p := hp1;
  4170. end;
  4171. end
  4172. {$ifndef x86_64}
  4173. else if (current_settings.optimizecputype < cpu_Pentium2) then
  4174. begin
  4175. { changes "shl $1, %reg" to "add %reg, %reg", which is the same on a 386,
  4176. but faster on a 486, and Tairable in both U and V pipes on the Pentium
  4177. (unlike shl, which is only Tairable in the U pipe) }
  4178. if taicpu(p).oper[0]^.val=1 then
  4179. begin
  4180. hp1 := taicpu.Op_reg_reg(A_ADD,taicpu(p).opsize,
  4181. taicpu(p).oper[1]^.reg, taicpu(p).oper[1]^.reg);
  4182. InsertLLItem(p.previous, p.next, hp1);
  4183. p.free;
  4184. p := hp1;
  4185. end
  4186. { changes "shl $2, %reg" to "lea (,%reg,4), %reg"
  4187. "shl $3, %reg" to "lea (,%reg,8), %reg }
  4188. else if (taicpu(p).opsize = S_L) and
  4189. (taicpu(p).oper[0]^.val<= 3) then
  4190. begin
  4191. reference_reset(tmpref,2,[]);
  4192. TmpRef.index := taicpu(p).oper[1]^.reg;
  4193. TmpRef.scalefactor := 1 shl taicpu(p).oper[0]^.val;
  4194. hp1 := taicpu.Op_ref_reg(A_LEA,S_L,TmpRef, taicpu(p).oper[1]^.reg);
  4195. InsertLLItem(p.previous, p.next, hp1);
  4196. p.free;
  4197. p := hp1;
  4198. end;
  4199. end
  4200. {$endif x86_64}
  4201. else if
  4202. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  4203. (
  4204. (
  4205. MatchInstruction(hp1, A_AND, [taicpu(p).opsize]) and
  4206. SetAndTest(hp1, hp2)
  4207. {$ifdef x86_64}
  4208. ) or
  4209. (
  4210. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  4211. GetNextInstruction(hp1, hp2) and
  4212. MatchInstruction(hp2, A_AND, [taicpu(p).opsize]) and
  4213. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4214. (taicpu(hp1).oper[1]^.reg = taicpu(hp2).oper[0]^.reg)
  4215. {$endif x86_64}
  4216. )
  4217. ) and
  4218. (taicpu(p).oper[1]^.reg = taicpu(hp2).oper[1]^.reg) then
  4219. begin
  4220. { Change:
  4221. shl x, %reg1
  4222. mov -(1<<x), %reg2
  4223. and %reg2, %reg1
  4224. Or:
  4225. shl x, %reg1
  4226. and -(1<<x), %reg1
  4227. To just:
  4228. shl x, %reg1
  4229. Since the and operation only zeroes bits that are already zero from the shl operation
  4230. }
  4231. case taicpu(p).oper[0]^.val of
  4232. 8:
  4233. mask:=$FFFFFFFFFFFFFF00;
  4234. 16:
  4235. mask:=$FFFFFFFFFFFF0000;
  4236. 32:
  4237. mask:=$FFFFFFFF00000000;
  4238. 63:
  4239. { Constant pre-calculated to prevent overflow errors with Int64 }
  4240. mask:=$8000000000000000;
  4241. else
  4242. begin
  4243. if taicpu(p).oper[0]^.val >= 64 then
  4244. { Shouldn't happen realistically, since the register
  4245. is guaranteed to be set to zero at this point }
  4246. mask := 0
  4247. else
  4248. mask := -(Int64(1 shl taicpu(p).oper[0]^.val));
  4249. end;
  4250. end;
  4251. if taicpu(hp1).oper[0]^.val = mask then
  4252. begin
  4253. { Everything checks out, perform the optimisation, as long as
  4254. the FLAGS register isn't being used}
  4255. TransferUsedRegs(TmpUsedRegs);
  4256. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4257. {$ifdef x86_64}
  4258. if (hp1 <> hp2) then
  4259. begin
  4260. { "shl/mov/and" version }
  4261. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  4262. { Don't do the optimisation if the FLAGS register is in use }
  4263. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)) then
  4264. begin
  4265. DebugMsg(SPeepholeOptimization + 'ShlMovAnd2Shl', p);
  4266. { Don't remove the 'mov' instruction if its register is used elsewhere }
  4267. if not(RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, hp2, TmpUsedRegs)) then
  4268. begin
  4269. RemoveInstruction(hp1);
  4270. Result := True;
  4271. end;
  4272. { Only set Result to True if the 'mov' instruction was removed }
  4273. RemoveInstruction(hp2);
  4274. end;
  4275. end
  4276. else
  4277. {$endif x86_64}
  4278. begin
  4279. { "shl/and" version }
  4280. { Don't do the optimisation if the FLAGS register is in use }
  4281. if not(RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)) then
  4282. begin
  4283. DebugMsg(SPeepholeOptimization + 'ShlAnd2Shl', p);
  4284. RemoveInstruction(hp1);
  4285. Result := True;
  4286. end;
  4287. end;
  4288. Exit;
  4289. end
  4290. else {$ifdef x86_64}if (hp1 = hp2) then{$endif x86_64}
  4291. begin
  4292. { Even if the mask doesn't allow for its removal, we might be
  4293. able to optimise the mask for the "shl/and" version, which
  4294. may permit other peephole optimisations }
  4295. {$ifdef DEBUG_AOPTCPU}
  4296. mask := taicpu(hp1).oper[0]^.val and mask;
  4297. if taicpu(hp1).oper[0]^.val <> mask then
  4298. begin
  4299. DebugMsg(
  4300. SPeepholeOptimization +
  4301. 'Changed mask from $' + debug_tostr(taicpu(hp1).oper[0]^.val) +
  4302. ' to $' + debug_tostr(mask) +
  4303. 'based on previous instruction (ShlAnd2ShlAnd)', hp1);
  4304. taicpu(hp1).oper[0]^.val := mask;
  4305. end;
  4306. {$else DEBUG_AOPTCPU}
  4307. { If debugging is off, just set the operand even if it's the same }
  4308. taicpu(hp1).oper[0]^.val := taicpu(hp1).oper[0]^.val and mask;
  4309. {$endif DEBUG_AOPTCPU}
  4310. end;
  4311. end;
  4312. {
  4313. change
  4314. shl/sal const,reg
  4315. <op> ...(...,reg,1),...
  4316. into
  4317. <op> ...(...,reg,1 shl const),...
  4318. if const in 1..3
  4319. }
  4320. if MatchOpType(taicpu(p), top_const, top_reg) and
  4321. (taicpu(p).oper[0]^.val in [1..3]) and
  4322. GetNextInstruction(p, hp1) and
  4323. MatchInstruction(hp1,A_MOV,A_LEA,[]) and
  4324. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  4325. (taicpu(p).oper[1]^.reg=taicpu(hp1).oper[0]^.ref^.index) and
  4326. (taicpu(p).oper[1]^.reg<>taicpu(hp1).oper[0]^.ref^.base) and
  4327. (taicpu(hp1).oper[0]^.ref^.scalefactor in [0,1]) then
  4328. begin
  4329. TransferUsedRegs(TmpUsedRegs);
  4330. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4331. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)) then
  4332. begin
  4333. taicpu(hp1).oper[0]^.ref^.scalefactor:=1 shl taicpu(p).oper[0]^.val;
  4334. DebugMsg(SPeepholeOptimization + 'ShlOp2Op', p);
  4335. RemoveCurrentP(p);
  4336. Result:=true;
  4337. end;
  4338. end;
  4339. end;
  4340. function TX86AsmOptimizer.CheckMemoryWrite(var first_mov, second_mov: taicpu): Boolean;
  4341. var
  4342. CurrentRef: TReference;
  4343. FullReg: TRegister;
  4344. hp1, hp2: tai;
  4345. begin
  4346. Result := False;
  4347. if (first_mov.opsize <> S_B) or (second_mov.opsize <> S_B) then
  4348. Exit;
  4349. { We assume you've checked if the operand is actually a reference by
  4350. this point. If it isn't, you'll most likely get an access violation }
  4351. CurrentRef := first_mov.oper[1]^.ref^;
  4352. { Memory must be aligned }
  4353. if (CurrentRef.offset mod 4) <> 0 then
  4354. Exit;
  4355. Inc(CurrentRef.offset);
  4356. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  4357. if MatchOperand(second_mov.oper[0]^, 0) and
  4358. references_equal(second_mov.oper[1]^.ref^, CurrentRef) and
  4359. GetNextInstruction(second_mov, hp1) and
  4360. (hp1.typ = ait_instruction) and
  4361. (taicpu(hp1).opcode = A_MOV) and
  4362. MatchOpType(taicpu(hp1), top_const, top_ref) and
  4363. (taicpu(hp1).oper[0]^.val = 0) then
  4364. begin
  4365. Inc(CurrentRef.offset);
  4366. CurrentRef.alignment := taicpu(hp1).oper[1]^.ref^.alignment; { Otherwise references_equal might return False }
  4367. FullReg := newreg(R_INTREGISTER,getsupreg(first_mov.oper[0]^.reg), R_SUBD);
  4368. if references_equal(taicpu(hp1).oper[1]^.ref^, CurrentRef) then
  4369. begin
  4370. case taicpu(hp1).opsize of
  4371. S_B:
  4372. if GetNextInstruction(hp1, hp2) and
  4373. MatchInstruction(taicpu(hp2), A_MOV, [S_B]) and
  4374. MatchOpType(taicpu(hp2), top_const, top_ref) and
  4375. (taicpu(hp2).oper[0]^.val = 0) then
  4376. begin
  4377. Inc(CurrentRef.offset);
  4378. CurrentRef.alignment := 1; { Otherwise references_equal will return False }
  4379. if references_equal(taicpu(hp2).oper[1]^.ref^, CurrentRef) and
  4380. (taicpu(hp2).opsize = S_B) then
  4381. begin
  4382. RemoveInstruction(hp1);
  4383. RemoveInstruction(hp2);
  4384. first_mov.opsize := S_L;
  4385. if first_mov.oper[0]^.typ = top_reg then
  4386. begin
  4387. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVZX/MOVl', first_mov);
  4388. { Reuse second_mov as a MOVZX instruction }
  4389. second_mov.opcode := A_MOVZX;
  4390. second_mov.opsize := S_BL;
  4391. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4392. second_mov.loadreg(1, FullReg);
  4393. first_mov.oper[0]^.reg := FullReg;
  4394. asml.Remove(second_mov);
  4395. asml.InsertBefore(second_mov, first_mov);
  4396. end
  4397. else
  4398. { It's a value }
  4399. begin
  4400. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVb/MOVb -> MOVl', first_mov);
  4401. RemoveInstruction(second_mov);
  4402. end;
  4403. Result := True;
  4404. Exit;
  4405. end;
  4406. end;
  4407. S_W:
  4408. begin
  4409. RemoveInstruction(hp1);
  4410. first_mov.opsize := S_L;
  4411. if first_mov.oper[0]^.typ = top_reg then
  4412. begin
  4413. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVZX/MOVl', first_mov);
  4414. { Reuse second_mov as a MOVZX instruction }
  4415. second_mov.opcode := A_MOVZX;
  4416. second_mov.opsize := S_BL;
  4417. second_mov.loadreg(0, first_mov.oper[0]^.reg);
  4418. second_mov.loadreg(1, FullReg);
  4419. first_mov.oper[0]^.reg := FullReg;
  4420. asml.Remove(second_mov);
  4421. asml.InsertBefore(second_mov, first_mov);
  4422. end
  4423. else
  4424. { It's a value }
  4425. begin
  4426. DebugMsg(SPeepholeOptimization + 'MOVb/MOVb/MOVw -> MOVl', first_mov);
  4427. RemoveInstruction(second_mov);
  4428. end;
  4429. Result := True;
  4430. Exit;
  4431. end;
  4432. else
  4433. ;
  4434. end;
  4435. end;
  4436. end;
  4437. end;
  4438. function TX86AsmOptimizer.OptPass1FSTP(var p: tai): boolean;
  4439. { returns true if a "continue" should be done after this optimization }
  4440. var
  4441. hp1, hp2: tai;
  4442. begin
  4443. Result := false;
  4444. if MatchOpType(taicpu(p),top_ref) and
  4445. GetNextInstruction(p, hp1) and
  4446. (hp1.typ = ait_instruction) and
  4447. (((taicpu(hp1).opcode = A_FLD) and
  4448. (taicpu(p).opcode = A_FSTP)) or
  4449. ((taicpu(p).opcode = A_FISTP) and
  4450. (taicpu(hp1).opcode = A_FILD))) and
  4451. MatchOpType(taicpu(hp1),top_ref) and
  4452. (taicpu(hp1).opsize = taicpu(p).opsize) and
  4453. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  4454. begin
  4455. { replacing fstp f;fld f by fst f is only valid for extended because of rounding or if fastmath is on }
  4456. if ((taicpu(p).opsize=S_FX) or (cs_opt_fastmath in current_settings.optimizerswitches)) and
  4457. GetNextInstruction(hp1, hp2) and
  4458. (hp2.typ = ait_instruction) and
  4459. IsExitCode(hp2) and
  4460. (taicpu(p).oper[0]^.ref^.base = current_procinfo.FramePointer) and
  4461. not(assigned(current_procinfo.procdef.funcretsym) and
  4462. (taicpu(p).oper[0]^.ref^.offset < tabstractnormalvarsym(current_procinfo.procdef.funcretsym).localloc.reference.offset)) and
  4463. (taicpu(p).oper[0]^.ref^.index = NR_NO) then
  4464. begin
  4465. RemoveInstruction(hp1);
  4466. RemoveCurrentP(p, hp2);
  4467. RemoveLastDeallocForFuncRes(p);
  4468. Result := true;
  4469. end
  4470. else
  4471. { we can do this only in fast math mode as fstp is rounding ...
  4472. ... still disabled as it breaks the compiler and/or rtl }
  4473. if ({ (cs_opt_fastmath in current_settings.optimizerswitches) or }
  4474. { ... or if another fstp equal to the first one follows }
  4475. (GetNextInstruction(hp1,hp2) and
  4476. (hp2.typ = ait_instruction) and
  4477. (taicpu(p).opcode=taicpu(hp2).opcode) and
  4478. (taicpu(p).opsize=taicpu(hp2).opsize))
  4479. ) and
  4480. { fst can't store an extended/comp value }
  4481. (taicpu(p).opsize <> S_FX) and
  4482. (taicpu(p).opsize <> S_IQ) then
  4483. begin
  4484. if (taicpu(p).opcode = A_FSTP) then
  4485. taicpu(p).opcode := A_FST
  4486. else
  4487. taicpu(p).opcode := A_FIST;
  4488. DebugMsg(SPeepholeOptimization + 'FstpFld2Fst',p);
  4489. RemoveInstruction(hp1);
  4490. end;
  4491. end;
  4492. end;
  4493. function TX86AsmOptimizer.OptPass1FLD(var p : tai) : boolean;
  4494. var
  4495. hp1, hp2: tai;
  4496. begin
  4497. result:=false;
  4498. if MatchOpType(taicpu(p),top_reg) and
  4499. GetNextInstruction(p, hp1) and
  4500. (hp1.typ = Ait_Instruction) and
  4501. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  4502. (taicpu(hp1).oper[0]^.reg = NR_ST) and
  4503. (taicpu(hp1).oper[1]^.reg = NR_ST1) then
  4504. { change to
  4505. fld reg fxxx reg,st
  4506. fxxxp st, st1 (hp1)
  4507. Remark: non commutative operations must be reversed!
  4508. }
  4509. begin
  4510. case taicpu(hp1).opcode Of
  4511. A_FMULP,A_FADDP,
  4512. A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  4513. begin
  4514. case taicpu(hp1).opcode Of
  4515. A_FADDP: taicpu(hp1).opcode := A_FADD;
  4516. A_FMULP: taicpu(hp1).opcode := A_FMUL;
  4517. A_FSUBP: taicpu(hp1).opcode := A_FSUBR;
  4518. A_FSUBRP: taicpu(hp1).opcode := A_FSUB;
  4519. A_FDIVP: taicpu(hp1).opcode := A_FDIVR;
  4520. A_FDIVRP: taicpu(hp1).opcode := A_FDIV;
  4521. else
  4522. internalerror(2019050534);
  4523. end;
  4524. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  4525. taicpu(hp1).oper[1]^.reg := NR_ST;
  4526. RemoveCurrentP(p, hp1);
  4527. Result:=true;
  4528. exit;
  4529. end;
  4530. else
  4531. ;
  4532. end;
  4533. end
  4534. else
  4535. if MatchOpType(taicpu(p),top_ref) and
  4536. GetNextInstruction(p, hp2) and
  4537. (hp2.typ = Ait_Instruction) and
  4538. MatchOpType(taicpu(hp2),top_reg,top_reg) and
  4539. (taicpu(p).opsize in [S_FS, S_FL]) and
  4540. (taicpu(hp2).oper[0]^.reg = NR_ST) and
  4541. (taicpu(hp2).oper[1]^.reg = NR_ST1) then
  4542. if GetLastInstruction(p, hp1) and
  4543. MatchInstruction(hp1,A_FLD,A_FST,[taicpu(p).opsize]) and
  4544. MatchOpType(taicpu(hp1),top_ref) and
  4545. RefsEqual(taicpu(p).oper[0]^.ref^, taicpu(hp1).oper[0]^.ref^) then
  4546. if ((taicpu(hp2).opcode = A_FMULP) or
  4547. (taicpu(hp2).opcode = A_FADDP)) then
  4548. { change to
  4549. fld/fst mem1 (hp1) fld/fst mem1
  4550. fld mem1 (p) fadd/
  4551. faddp/ fmul st, st
  4552. fmulp st, st1 (hp2) }
  4553. begin
  4554. RemoveCurrentP(p, hp1);
  4555. if (taicpu(hp2).opcode = A_FADDP) then
  4556. taicpu(hp2).opcode := A_FADD
  4557. else
  4558. taicpu(hp2).opcode := A_FMUL;
  4559. taicpu(hp2).oper[1]^.reg := NR_ST;
  4560. end
  4561. else
  4562. { change to
  4563. fld/fst mem1 (hp1) fld/fst mem1
  4564. fld mem1 (p) fld st}
  4565. begin
  4566. taicpu(p).changeopsize(S_FL);
  4567. taicpu(p).loadreg(0,NR_ST);
  4568. end
  4569. else
  4570. begin
  4571. case taicpu(hp2).opcode Of
  4572. A_FMULP,A_FADDP,A_FSUBP,A_FDIVP,A_FSUBRP,A_FDIVRP:
  4573. { change to
  4574. fld/fst mem1 (hp1) fld/fst mem1
  4575. fld mem2 (p) fxxx mem2
  4576. fxxxp st, st1 (hp2) }
  4577. begin
  4578. case taicpu(hp2).opcode Of
  4579. A_FADDP: taicpu(p).opcode := A_FADD;
  4580. A_FMULP: taicpu(p).opcode := A_FMUL;
  4581. A_FSUBP: taicpu(p).opcode := A_FSUBR;
  4582. A_FSUBRP: taicpu(p).opcode := A_FSUB;
  4583. A_FDIVP: taicpu(p).opcode := A_FDIVR;
  4584. A_FDIVRP: taicpu(p).opcode := A_FDIV;
  4585. else
  4586. internalerror(2019050533);
  4587. end;
  4588. RemoveInstruction(hp2);
  4589. end
  4590. else
  4591. ;
  4592. end
  4593. end
  4594. end;
  4595. function IsCmpSubset(cond1, cond2: TAsmCond): Boolean; inline;
  4596. begin
  4597. Result := condition_in(cond1, cond2) or
  4598. { Not strictly subsets due to the actual flags checked, but because we're
  4599. comparing integers, E is a subset of AE and GE and their aliases }
  4600. ((cond1 in [C_E, C_Z]) and (cond2 in [C_AE, C_NB, C_NC, C_GE, C_NL]));
  4601. end;
  4602. function TX86AsmOptimizer.OptPass1Cmp(var p: tai): boolean;
  4603. var
  4604. v: TCGInt;
  4605. hp1, hp2, p_dist, p_jump, hp1_dist, p_label, hp1_label: tai;
  4606. FirstMatch: Boolean;
  4607. JumpLabel, JumpLabel_dist, JumpLabel_far: TAsmLabel;
  4608. begin
  4609. Result:=false;
  4610. { All these optimisations need a next instruction }
  4611. if not GetNextInstruction(p, hp1) then
  4612. Exit;
  4613. { Search for:
  4614. cmp ###,###
  4615. j(c1) @lbl1
  4616. ...
  4617. @lbl:
  4618. cmp ###.### (same comparison as above)
  4619. j(c2) @lbl2
  4620. If c1 is a subset of c2, change to:
  4621. cmp ###,###
  4622. j(c2) @lbl2
  4623. (@lbl1 may become a dead label as a result)
  4624. }
  4625. { Also handle cases where there are multiple jumps in a row }
  4626. p_jump := hp1;
  4627. while Assigned(p_jump) and MatchInstruction(p_jump, A_JCC, []) do
  4628. begin
  4629. if IsJumpToLabel(taicpu(p_jump)) then
  4630. begin
  4631. JumpLabel := TAsmLabel(taicpu(p_jump).oper[0]^.ref^.symbol);
  4632. p_label := nil;
  4633. if Assigned(JumpLabel) then
  4634. p_label := getlabelwithsym(JumpLabel);
  4635. if Assigned(p_label) and
  4636. GetNextInstruction(p_label, p_dist) and
  4637. MatchInstruction(p_dist, A_CMP, []) and
  4638. MatchOperand(taicpu(p_dist).oper[0]^, taicpu(p).oper[0]^) and
  4639. MatchOperand(taicpu(p_dist).oper[1]^, taicpu(p).oper[1]^) and
  4640. GetNextInstruction(p_dist, hp1_dist) and
  4641. MatchInstruction(hp1_dist, A_JCC, []) then { This doesn't have to be an explicit label }
  4642. begin
  4643. JumpLabel_dist := TAsmLabel(taicpu(hp1_dist).oper[0]^.ref^.symbol);
  4644. if JumpLabel = JumpLabel_dist then
  4645. { This is an infinite loop }
  4646. Exit;
  4647. { Best optimisation when the first condition is a subset (or equal) of the second }
  4648. if IsCmpSubset(taicpu(p_jump).condition, taicpu(hp1_dist).condition) then
  4649. begin
  4650. { Any registers used here will already be allocated }
  4651. if Assigned(JumpLabel_dist) then
  4652. JumpLabel_dist.IncRefs;
  4653. if Assigned(JumpLabel) then
  4654. JumpLabel.DecRefs;
  4655. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc -> CMP/Jcc, redirecting first jump', p_jump);
  4656. taicpu(p_jump).condition := taicpu(hp1_dist).condition;
  4657. taicpu(p_jump).loadref(0, taicpu(hp1_dist).oper[0]^.ref^);
  4658. Result := True;
  4659. { Don't exit yet. Since p and p_jump haven't actually been
  4660. removed, we can check for more on this iteration }
  4661. end
  4662. else if IsCmpSubset(taicpu(hp1_dist).condition, inverse_cond(taicpu(p_jump).condition)) and
  4663. GetNextInstruction(hp1_dist, hp1_label) and
  4664. SkipAligns(hp1_label, hp1_label) and
  4665. (hp1_label.typ = ait_label) then
  4666. begin
  4667. JumpLabel_far := tai_label(hp1_label).labsym;
  4668. if (JumpLabel_far = JumpLabel_dist) or (JumpLabel_far = JumpLabel) then
  4669. { This is an infinite loop }
  4670. Exit;
  4671. if Assigned(JumpLabel_far) then
  4672. begin
  4673. { In this situation, if the first jump branches, the second one will never,
  4674. branch so change the destination label to after the second jump }
  4675. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/@Lbl/CMP/Jcc/@Lbl -> CMP/Jcc, redirecting first jump to 2nd label', p_jump);
  4676. if Assigned(JumpLabel) then
  4677. JumpLabel.DecRefs;
  4678. JumpLabel_far.IncRefs;
  4679. taicpu(p_jump).oper[0]^.ref^.symbol := JumpLabel_far;
  4680. Result := True;
  4681. { Don't exit yet. Since p and p_jump haven't actually been
  4682. removed, we can check for more on this iteration }
  4683. Continue;
  4684. end;
  4685. end;
  4686. end;
  4687. end;
  4688. { Search for:
  4689. cmp ###,###
  4690. j(c1) @lbl1
  4691. cmp ###,### (same as first)
  4692. Remove second cmp
  4693. }
  4694. if GetNextInstruction(p_jump, hp2) and
  4695. (
  4696. (
  4697. MatchInstruction(hp2, A_CMP, []) and
  4698. (
  4699. (
  4700. MatchOpType(taicpu(p), top_const, top_reg) and
  4701. (taicpu(hp2).oper[0]^.val = taicpu(p).oper[0]^.val) and
  4702. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  4703. ) or (
  4704. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[0]^) and
  4705. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^)
  4706. )
  4707. )
  4708. ) or (
  4709. { Also match cmp $0,%reg; jcc @lbl; test %reg,%reg }
  4710. MatchOperand(taicpu(p).oper[0]^, 0) and
  4711. (taicpu(p).oper[1]^.typ = top_reg) and
  4712. MatchInstruction(hp2, A_TEST, []) and
  4713. MatchOpType(taicpu(hp2), top_reg, top_reg) and
  4714. (taicpu(hp2).oper[0]^.reg = taicpu(hp2).oper[1]^.reg) and
  4715. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp2).oper[1]^.reg)
  4716. )
  4717. ) then
  4718. begin
  4719. DebugMsg(SPeepholeOptimization + 'CMP/Jcc/CMP; removed superfluous CMP', hp2);
  4720. RemoveInstruction(hp2);
  4721. Result := True;
  4722. { Continue the while loop in case "Jcc/CMP" follows the second CMP that was just removed }
  4723. end;
  4724. GetNextInstruction(p_jump, p_jump);
  4725. end;
  4726. if taicpu(p).oper[0]^.typ = top_const then
  4727. begin
  4728. if (taicpu(p).oper[0]^.val = 0) and
  4729. (taicpu(p).oper[1]^.typ = top_reg) and
  4730. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) then
  4731. begin
  4732. hp2 := p;
  4733. FirstMatch := True;
  4734. { When dealing with "cmp $0,%reg", only ZF and SF contain
  4735. anything meaningful once it's converted to "test %reg,%reg";
  4736. additionally, some jumps will always (or never) branch, so
  4737. evaluate every jump immediately following the
  4738. comparison, optimising the conditions if possible.
  4739. Similarly with SETcc... those that are always set to 0 or 1
  4740. are changed to MOV instructions }
  4741. while FirstMatch or { Saves calling GetNextInstruction unnecessarily }
  4742. (
  4743. GetNextInstruction(hp2, hp1) and
  4744. MatchInstruction(hp1,A_Jcc,A_SETcc,[])
  4745. ) do
  4746. begin
  4747. FirstMatch := False;
  4748. case taicpu(hp1).condition of
  4749. C_B, C_C, C_NAE, C_O:
  4750. { For B/NAE:
  4751. Will never branch since an unsigned integer can never be below zero
  4752. For C/O:
  4753. Result cannot overflow because 0 is being subtracted
  4754. }
  4755. begin
  4756. if taicpu(hp1).opcode = A_Jcc then
  4757. begin
  4758. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (jump removed)', hp1);
  4759. TAsmLabel(taicpu(hp1).oper[0]^.ref^.symbol).decrefs;
  4760. RemoveInstruction(hp1);
  4761. { Since hp1 was deleted, hp2 must not be updated }
  4762. Continue;
  4763. end
  4764. else
  4765. begin
  4766. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition B/C/NAE/O --> Never (set -> mov 0)', hp1);
  4767. { Convert "set(c) %reg" instruction to "movb 0,%reg" }
  4768. taicpu(hp1).opcode := A_MOV;
  4769. taicpu(hp1).ops := 2;
  4770. taicpu(hp1).condition := C_None;
  4771. taicpu(hp1).opsize := S_B;
  4772. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  4773. taicpu(hp1).loadconst(0, 0);
  4774. end;
  4775. end;
  4776. C_BE, C_NA:
  4777. begin
  4778. { Will only branch if equal to zero }
  4779. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition BE/NA --> E', hp1);
  4780. taicpu(hp1).condition := C_E;
  4781. end;
  4782. C_A, C_NBE:
  4783. begin
  4784. { Will only branch if not equal to zero }
  4785. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition A/NBE --> NE', hp1);
  4786. taicpu(hp1).condition := C_NE;
  4787. end;
  4788. C_AE, C_NB, C_NC, C_NO:
  4789. begin
  4790. { Will always branch }
  4791. DebugMsg(SPeepholeOptimization + 'Cmpcc2Testcc - condition AE/NB/NC/NO --> Always', hp1);
  4792. if taicpu(hp1).opcode = A_Jcc then
  4793. begin
  4794. MakeUnconditional(taicpu(hp1));
  4795. { Any jumps/set that follow will now be dead code }
  4796. RemoveDeadCodeAfterJump(taicpu(hp1));
  4797. Break;
  4798. end
  4799. else
  4800. begin
  4801. { Convert "set(c) %reg" instruction to "movb 1,%reg" }
  4802. taicpu(hp1).opcode := A_MOV;
  4803. taicpu(hp1).ops := 2;
  4804. taicpu(hp1).condition := C_None;
  4805. taicpu(hp1).opsize := S_B;
  4806. taicpu(hp1).loadreg(1,taicpu(hp1).oper[0]^.reg);
  4807. taicpu(hp1).loadconst(0, 1);
  4808. end;
  4809. end;
  4810. C_None:
  4811. InternalError(2020012201);
  4812. C_P, C_PE, C_NP, C_PO:
  4813. { We can't handle parity checks and they should never be generated
  4814. after a general-purpose CMP (it's used in some floating-point
  4815. comparisons that don't use CMP) }
  4816. InternalError(2020012202);
  4817. else
  4818. { Zero/Equality, Sign, their complements and all of the
  4819. signed comparisons do not need to be converted };
  4820. end;
  4821. hp2 := hp1;
  4822. end;
  4823. { Convert the instruction to a TEST }
  4824. taicpu(p).opcode := A_TEST;
  4825. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  4826. Result := True;
  4827. Exit;
  4828. end
  4829. else if (taicpu(p).oper[0]^.val = 1) and
  4830. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  4831. (taicpu(hp1).condition in [C_L, C_NGE]) then
  4832. begin
  4833. { Convert; To:
  4834. cmp $1,r/m cmp $0,r/m
  4835. jl @lbl jle @lbl
  4836. }
  4837. DebugMsg(SPeepholeOptimization + 'Cmp1Jl2Cmp0Jle', p);
  4838. taicpu(p).oper[0]^.val := 0;
  4839. taicpu(hp1).condition := C_LE;
  4840. { If the instruction is now "cmp $0,%reg", convert it to a
  4841. TEST (and effectively do the work of the "cmp $0,%reg" in
  4842. the block above)
  4843. If it's a reference, we can get away with not setting
  4844. Result to True because he haven't evaluated the jump
  4845. in this pass yet.
  4846. }
  4847. if (taicpu(p).oper[1]^.typ = top_reg) then
  4848. begin
  4849. taicpu(p).opcode := A_TEST;
  4850. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  4851. Result := True;
  4852. end;
  4853. Exit;
  4854. end
  4855. else if (taicpu(p).oper[1]^.typ = top_reg) then
  4856. begin
  4857. { cmp register,$8000 neg register
  4858. je target --> jo target
  4859. .... only if register is deallocated before jump.}
  4860. case Taicpu(p).opsize of
  4861. S_B: v:=$80;
  4862. S_W: v:=$8000;
  4863. S_L: v:=qword($80000000);
  4864. { S_Q will never happen: cmp with 64 bit constants is not possible }
  4865. S_Q:
  4866. Exit;
  4867. else
  4868. internalerror(2013112905);
  4869. end;
  4870. if (taicpu(p).oper[0]^.val=v) and
  4871. MatchInstruction(hp1,A_Jcc,A_SETcc,[]) and
  4872. (Taicpu(hp1).condition in [C_E,C_NE]) then
  4873. begin
  4874. TransferUsedRegs(TmpUsedRegs);
  4875. UpdateUsedRegs(TmpUsedRegs,tai(p.next));
  4876. if not(RegInUsedRegs(Taicpu(p).oper[1]^.reg, TmpUsedRegs)) then
  4877. begin
  4878. DebugMsg(SPeepholeOptimization + 'CmpJe2NegJo done',p);
  4879. Taicpu(p).opcode:=A_NEG;
  4880. Taicpu(p).loadoper(0,Taicpu(p).oper[1]^);
  4881. Taicpu(p).clearop(1);
  4882. Taicpu(p).ops:=1;
  4883. if Taicpu(hp1).condition=C_E then
  4884. Taicpu(hp1).condition:=C_O
  4885. else
  4886. Taicpu(hp1).condition:=C_NO;
  4887. Result:=true;
  4888. exit;
  4889. end;
  4890. end;
  4891. end;
  4892. end;
  4893. if (taicpu(p).oper[1]^.typ = top_reg) and
  4894. MatchInstruction(hp1,A_MOV,[]) and
  4895. not RegInInstruction(taicpu(p).oper[1]^.reg, hp1) and
  4896. (
  4897. (taicpu(p).oper[0]^.typ <> top_reg) or
  4898. not RegInInstruction(taicpu(p).oper[0]^.reg, hp1)
  4899. ) then
  4900. begin
  4901. { If we have something like:
  4902. cmp ###,%reg1
  4903. mov 0,%reg2
  4904. And no registers are shared, move the MOV command to before the
  4905. comparison as this means it can be optimised without worrying
  4906. about the FLAGS register. (This combination is generated by
  4907. "J(c)Mov1JmpMov0 -> Set(~c)", among other things).
  4908. }
  4909. SwapMovCmp(p, hp1);
  4910. Result := True;
  4911. Exit;
  4912. end;
  4913. end;
  4914. function TX86AsmOptimizer.OptPass1PXor(var p: tai): boolean;
  4915. var
  4916. hp1: tai;
  4917. begin
  4918. {
  4919. remove the second (v)pxor from
  4920. pxor reg,reg
  4921. ...
  4922. pxor reg,reg
  4923. }
  4924. Result:=false;
  4925. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  4926. MatchOpType(taicpu(p),top_reg,top_reg) and
  4927. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  4928. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4929. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  4930. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^) then
  4931. begin
  4932. DebugMsg(SPeepholeOptimization + 'PXorPXor2PXor done',hp1);
  4933. RemoveInstruction(hp1);
  4934. Result:=true;
  4935. Exit;
  4936. end
  4937. {
  4938. replace
  4939. pxor reg1,reg1
  4940. movapd/s reg1,reg2
  4941. dealloc reg1
  4942. by
  4943. pxor reg2,reg2
  4944. }
  4945. else if GetNextInstruction(p,hp1) and
  4946. { we mix single and double opperations here because we assume that the compiler
  4947. generates vmovapd only after double operations and vmovaps only after single operations }
  4948. MatchInstruction(hp1,A_MOVAPD,A_MOVAPS,[S_NO]) and
  4949. MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^) and
  4950. MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^) and
  4951. (taicpu(p).oper[0]^.typ=top_reg) then
  4952. begin
  4953. TransferUsedRegs(TmpUsedRegs);
  4954. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  4955. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  4956. begin
  4957. taicpu(p).loadoper(0,taicpu(hp1).oper[1]^);
  4958. taicpu(p).loadoper(1,taicpu(hp1).oper[1]^);
  4959. DebugMsg(SPeepholeOptimization + 'PXorMovapd2PXor done',p);
  4960. RemoveInstruction(hp1);
  4961. result:=true;
  4962. end;
  4963. end;
  4964. end;
  4965. function TX86AsmOptimizer.OptPass1VPXor(var p: tai): boolean;
  4966. var
  4967. hp1: tai;
  4968. begin
  4969. {
  4970. remove the second (v)pxor from
  4971. (v)pxor reg,reg
  4972. ...
  4973. (v)pxor reg,reg
  4974. }
  4975. Result:=false;
  4976. if MatchOperand(taicpu(p).oper[0]^,taicpu(p).oper[1]^,taicpu(p).oper[2]^) and
  4977. MatchOpType(taicpu(p),top_reg,top_reg,top_reg) and
  4978. GetNextInstructionUsingReg(p,hp1,taicpu(p).oper[0]^.reg) and
  4979. MatchInstruction(hp1,taicpu(p).opcode,[taicpu(p).opsize]) and
  4980. MatchOperand(taicpu(p).oper[0]^,taicpu(hp1).oper[0]^) and
  4981. MatchOperand(taicpu(hp1).oper[0]^,taicpu(hp1).oper[1]^,taicpu(hp1).oper[2]^) then
  4982. begin
  4983. DebugMsg(SPeepholeOptimization + 'VPXorVPXor2PXor done',hp1);
  4984. RemoveInstruction(hp1);
  4985. Result:=true;
  4986. Exit;
  4987. end
  4988. else
  4989. Result:=OptPass1VOP(p);
  4990. end;
  4991. function TX86AsmOptimizer.OptPass1Imul(var p: tai): boolean;
  4992. var
  4993. hp1 : tai;
  4994. begin
  4995. result:=false;
  4996. { replace
  4997. IMul const,%mreg1,%mreg2
  4998. Mov %reg2,%mreg3
  4999. dealloc %mreg3
  5000. by
  5001. Imul const,%mreg1,%mreg23
  5002. }
  5003. if (taicpu(p).ops=3) and
  5004. GetNextInstruction(p,hp1) and
  5005. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5006. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  5007. (taicpu(hp1).oper[1]^.typ=top_reg) then
  5008. begin
  5009. TransferUsedRegs(TmpUsedRegs);
  5010. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5011. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  5012. begin
  5013. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  5014. DebugMsg(SPeepholeOptimization + 'ImulMov2Imul done',p);
  5015. RemoveInstruction(hp1);
  5016. result:=true;
  5017. end;
  5018. end;
  5019. end;
  5020. function TX86AsmOptimizer.OptPass1SHXX(var p: tai): boolean;
  5021. var
  5022. hp1 : tai;
  5023. begin
  5024. result:=false;
  5025. { replace
  5026. IMul %reg0,%reg1,%reg2
  5027. Mov %reg2,%reg3
  5028. dealloc %reg2
  5029. by
  5030. Imul %reg0,%reg1,%reg3
  5031. }
  5032. if GetNextInstruction(p,hp1) and
  5033. MatchInstruction(hp1,A_MOV,[taicpu(p).opsize]) and
  5034. MatchOperand(taicpu(p).oper[2]^,taicpu(hp1).oper[0]^) and
  5035. (taicpu(hp1).oper[1]^.typ=top_reg) then
  5036. begin
  5037. TransferUsedRegs(TmpUsedRegs);
  5038. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5039. if not(RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg,hp1,TmpUsedRegs)) then
  5040. begin
  5041. taicpu(p).loadoper(2,taicpu(hp1).oper[1]^);
  5042. DebugMsg(SPeepholeOptimization + 'SHXXMov2SHXX done',p);
  5043. RemoveInstruction(hp1);
  5044. result:=true;
  5045. end;
  5046. end;
  5047. end;
  5048. function TX86AsmOptimizer.OptPass1Jcc(var p : tai) : boolean;
  5049. var
  5050. hp1, hp2, hp3, hp4, hp5: tai;
  5051. ThisReg: TRegister;
  5052. begin
  5053. Result := False;
  5054. if not GetNextInstruction(p,hp1) or (hp1.typ <> ait_instruction) then
  5055. Exit;
  5056. {
  5057. convert
  5058. j<c> .L1
  5059. mov 1,reg
  5060. jmp .L2
  5061. .L1
  5062. mov 0,reg
  5063. .L2
  5064. into
  5065. mov 0,reg
  5066. set<not(c)> reg
  5067. take care of alignment and that the mov 0,reg is not converted into a xor as this
  5068. would destroy the flag contents
  5069. Use MOVZX if size is preferred, since while mov 0,reg is bigger, it can be
  5070. executed at the same time as a previous comparison.
  5071. set<not(c)> reg
  5072. movzx reg, reg
  5073. }
  5074. if MatchInstruction(hp1,A_MOV,[]) and
  5075. (taicpu(hp1).oper[0]^.typ = top_const) and
  5076. (
  5077. (
  5078. (taicpu(hp1).oper[1]^.typ = top_reg)
  5079. {$ifdef i386}
  5080. { Under i386, ESI, EDI, EBP and ESP
  5081. don't have an 8-bit representation }
  5082. and not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  5083. {$endif i386}
  5084. ) or (
  5085. {$ifdef i386}
  5086. (taicpu(hp1).oper[1]^.typ <> top_reg) and
  5087. {$endif i386}
  5088. (taicpu(hp1).opsize = S_B)
  5089. )
  5090. ) and
  5091. GetNextInstruction(hp1,hp2) and
  5092. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  5093. GetNextInstruction(hp2,hp3) and
  5094. SkipAligns(hp3, hp3) and
  5095. (hp3.typ=ait_label) and
  5096. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  5097. GetNextInstruction(hp3,hp4) and
  5098. MatchInstruction(hp4,A_MOV,[taicpu(hp1).opsize]) and
  5099. (taicpu(hp4).oper[0]^.typ = top_const) and
  5100. (
  5101. ((taicpu(hp1).oper[0]^.val = 0) and (taicpu(hp4).oper[0]^.val = 1)) or
  5102. ((taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0))
  5103. ) and
  5104. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  5105. GetNextInstruction(hp4,hp5) and
  5106. SkipAligns(hp5, hp5) and
  5107. (hp5.typ=ait_label) and
  5108. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) then
  5109. begin
  5110. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5111. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  5112. tai_label(hp3).labsym.DecRefs;
  5113. { If this isn't the only reference to the middle label, we can
  5114. still make a saving - only that the first jump and everything
  5115. that follows will remain. }
  5116. if (tai_label(hp3).labsym.getrefs = 0) then
  5117. begin
  5118. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5119. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c)',p)
  5120. else
  5121. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c)',p);
  5122. { remove jump, first label and second MOV (also catching any aligns) }
  5123. repeat
  5124. if not GetNextInstruction(hp2, hp3) then
  5125. InternalError(2021040810);
  5126. RemoveInstruction(hp2);
  5127. hp2 := hp3;
  5128. until hp2 = hp5;
  5129. { Don't decrement reference count before the removal loop
  5130. above, otherwise GetNextInstruction won't stop on the
  5131. the label }
  5132. tai_label(hp5).labsym.DecRefs;
  5133. end
  5134. else
  5135. begin
  5136. if (taicpu(hp1).oper[0]^.val = 1) and (taicpu(hp4).oper[0]^.val = 0) then
  5137. DebugMsg(SPeepholeOptimization + 'J(c)Mov1JmpMov0 -> Set(~c) (partial)',p)
  5138. else
  5139. DebugMsg(SPeepholeOptimization + 'J(c)Mov0JmpMov1 -> Set(c) (partial)',p);
  5140. end;
  5141. taicpu(p).opcode:=A_SETcc;
  5142. taicpu(p).opsize:=S_B;
  5143. taicpu(p).is_jmp:=False;
  5144. if taicpu(hp1).opsize=S_B then
  5145. begin
  5146. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  5147. RemoveInstruction(hp1);
  5148. end
  5149. else
  5150. begin
  5151. { Will be a register because the size can't be S_B otherwise }
  5152. ThisReg := newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBL);
  5153. taicpu(p).loadreg(0, ThisReg);
  5154. if (cs_opt_size in current_settings.optimizerswitches) and IsMOVZXAcceptable then
  5155. begin
  5156. case taicpu(hp1).opsize of
  5157. S_W:
  5158. taicpu(hp1).opsize := S_BW;
  5159. S_L:
  5160. taicpu(hp1).opsize := S_BL;
  5161. {$ifdef x86_64}
  5162. S_Q:
  5163. begin
  5164. taicpu(hp1).opsize := S_BL;
  5165. { Change the destination register to 32-bit }
  5166. taicpu(hp1).loadreg(1, newreg(R_INTREGISTER,getsupreg(ThisReg), R_SUBD));
  5167. end;
  5168. {$endif x86_64}
  5169. else
  5170. InternalError(2021040820);
  5171. end;
  5172. taicpu(hp1).opcode := A_MOVZX;
  5173. taicpu(hp1).loadreg(0, ThisReg);
  5174. end
  5175. else
  5176. begin
  5177. AllocRegBetween(NR_FLAGS,p,hp1,UsedRegs);
  5178. { hp1 is already a MOV instruction with the correct register }
  5179. taicpu(hp1).loadconst(0, 0);
  5180. { Inserting it right before p will guarantee that the flags are also tracked }
  5181. asml.Remove(hp1);
  5182. asml.InsertBefore(hp1, p);
  5183. end;
  5184. end;
  5185. Result:=true;
  5186. exit;
  5187. end
  5188. end;
  5189. function TX86AsmOptimizer.CheckJumpMovTransferOpt(var p: tai; hp1: tai; LoopCount: Integer; out Count: Integer): Boolean;
  5190. var
  5191. hp2, hp3, first_assignment: tai;
  5192. IncCount, OperIdx: Integer;
  5193. OrigLabel: TAsmLabel;
  5194. begin
  5195. Count := 0;
  5196. Result := False;
  5197. first_assignment := nil;
  5198. if (LoopCount >= 20) then
  5199. begin
  5200. { Guard against infinite loops }
  5201. Exit;
  5202. end;
  5203. if (taicpu(p).oper[0]^.typ <> top_ref) or
  5204. (taicpu(p).oper[0]^.ref^.refaddr <> addr_full) or
  5205. (taicpu(p).oper[0]^.ref^.base <> NR_NO) or
  5206. (taicpu(p).oper[0]^.ref^.index <> NR_NO) or
  5207. not (taicpu(p).oper[0]^.ref^.symbol is TAsmLabel) then
  5208. Exit;
  5209. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  5210. {
  5211. change
  5212. jmp .L1
  5213. ...
  5214. .L1:
  5215. mov ##, ## ( multiple movs possible )
  5216. jmp/ret
  5217. into
  5218. mov ##, ##
  5219. jmp/ret
  5220. }
  5221. if not Assigned(hp1) then
  5222. begin
  5223. hp1 := GetLabelWithSym(OrigLabel);
  5224. if not Assigned(hp1) or not SkipLabels(hp1, hp1) then
  5225. Exit;
  5226. end;
  5227. hp2 := hp1;
  5228. while Assigned(hp2) do
  5229. begin
  5230. if Assigned(hp2) and (hp2.typ in [ait_label, ait_align]) then
  5231. SkipLabels(hp2,hp2);
  5232. if not Assigned(hp2) or (hp2.typ <> ait_instruction) then
  5233. Break;
  5234. case taicpu(hp2).opcode of
  5235. A_MOVSS:
  5236. begin
  5237. if taicpu(hp2).ops = 0 then
  5238. { Wrong MOVSS }
  5239. Break;
  5240. Inc(Count);
  5241. if Count >= 5 then
  5242. { Too many to be worthwhile }
  5243. Break;
  5244. GetNextInstruction(hp2, hp2);
  5245. Continue;
  5246. end;
  5247. A_MOV,
  5248. A_MOVD,
  5249. A_MOVQ,
  5250. A_MOVSX,
  5251. {$ifdef x86_64}
  5252. A_MOVSXD,
  5253. {$endif x86_64}
  5254. A_MOVZX,
  5255. A_MOVAPS,
  5256. A_MOVUPS,
  5257. A_MOVSD,
  5258. A_MOVAPD,
  5259. A_MOVUPD,
  5260. A_MOVDQA,
  5261. A_MOVDQU,
  5262. A_VMOVSS,
  5263. A_VMOVAPS,
  5264. A_VMOVUPS,
  5265. A_VMOVSD,
  5266. A_VMOVAPD,
  5267. A_VMOVUPD,
  5268. A_VMOVDQA,
  5269. A_VMOVDQU:
  5270. begin
  5271. Inc(Count);
  5272. if Count >= 5 then
  5273. { Too many to be worthwhile }
  5274. Break;
  5275. GetNextInstruction(hp2, hp2);
  5276. Continue;
  5277. end;
  5278. A_JMP:
  5279. begin
  5280. { Guard against infinite loops }
  5281. if taicpu(hp2).oper[0]^.ref^.symbol = OrigLabel then
  5282. Exit;
  5283. { Analyse this jump first in case it also duplicates assignments }
  5284. if CheckJumpMovTransferOpt(hp2, nil, LoopCount + 1, IncCount) then
  5285. begin
  5286. { Something did change! }
  5287. Result := True;
  5288. Inc(Count, IncCount);
  5289. if Count >= 5 then
  5290. begin
  5291. { Too many to be worthwhile }
  5292. Exit;
  5293. end;
  5294. if MatchInstruction(hp2, [A_JMP, A_RET], []) then
  5295. Break;
  5296. end;
  5297. Result := True;
  5298. Break;
  5299. end;
  5300. A_RET:
  5301. begin
  5302. Result := True;
  5303. Break;
  5304. end;
  5305. else
  5306. Break;
  5307. end;
  5308. end;
  5309. if Result then
  5310. begin
  5311. { A count of zero can happen when CheckJumpMovTransferOpt is called recursively }
  5312. if Count = 0 then
  5313. begin
  5314. Result := False;
  5315. Exit;
  5316. end;
  5317. hp3 := p;
  5318. DebugMsg(SPeepholeOptimization + 'Duplicated ' + debug_tostr(Count) + ' assignment(s) and redirected jump', p);
  5319. while True do
  5320. begin
  5321. if Assigned(hp1) and (hp1.typ in [ait_label, ait_align]) then
  5322. SkipLabels(hp1,hp1);
  5323. if (hp1.typ <> ait_instruction) then
  5324. InternalError(2021040720);
  5325. case taicpu(hp1).opcode of
  5326. A_JMP:
  5327. begin
  5328. { Change the original jump to the new destination }
  5329. OrigLabel.decrefs;
  5330. taicpu(hp1).oper[0]^.ref^.symbol.increfs;
  5331. taicpu(p).loadref(0, taicpu(hp1).oper[0]^.ref^);
  5332. { Set p to the first duplicated assignment so it can get optimised if needs be }
  5333. if not Assigned(first_assignment) then
  5334. InternalError(2021040810)
  5335. else
  5336. p := first_assignment;
  5337. Exit;
  5338. end;
  5339. A_RET:
  5340. begin
  5341. { Now change the jump into a RET instruction }
  5342. ConvertJumpToRET(p, hp1);
  5343. { Set p to the first duplicated assignment so it can get optimised if needs be }
  5344. if not Assigned(first_assignment) then
  5345. InternalError(2021040811)
  5346. else
  5347. p := first_assignment;
  5348. Exit;
  5349. end;
  5350. else
  5351. begin
  5352. { Duplicate the MOV instruction }
  5353. hp3:=tai(hp1.getcopy);
  5354. if first_assignment = nil then
  5355. first_assignment := hp3;
  5356. asml.InsertBefore(hp3, p);
  5357. { Make sure the compiler knows about any final registers written here }
  5358. for OperIdx := 0 to taicpu(hp3).ops - 1 do
  5359. with taicpu(hp3).oper[OperIdx]^ do
  5360. begin
  5361. case typ of
  5362. top_ref:
  5363. begin
  5364. if (ref^.base <> NR_NO) and
  5365. (getsupreg(ref^.base) <> RS_ESP) and
  5366. (getsupreg(ref^.base) <> RS_EBP)
  5367. {$ifdef x86_64} and (ref^.base <> NR_RIP) {$endif x86_64}
  5368. then
  5369. AllocRegBetween(ref^.base, hp3, tai(p.Next), UsedRegs);
  5370. if (ref^.index <> NR_NO) and
  5371. (getsupreg(ref^.index) <> RS_ESP) and
  5372. (getsupreg(ref^.index) <> RS_EBP)
  5373. {$ifdef x86_64} and (ref^.index <> NR_RIP) {$endif x86_64} and
  5374. (ref^.index <> ref^.base) then
  5375. AllocRegBetween(ref^.index, hp3, tai(p.Next), UsedRegs);
  5376. end;
  5377. top_reg:
  5378. AllocRegBetween(reg, hp3, tai(p.Next), UsedRegs);
  5379. else
  5380. ;
  5381. end;
  5382. end;
  5383. end;
  5384. end;
  5385. if not GetNextInstruction(hp1, hp1) then
  5386. { Should have dropped out earlier }
  5387. InternalError(2021040710);
  5388. end;
  5389. end;
  5390. end;
  5391. procedure TX86AsmOptimizer.SwapMovCmp(var p, hp1: tai);
  5392. var
  5393. hp2: tai;
  5394. X: Integer;
  5395. begin
  5396. asml.Remove(hp1);
  5397. { Try to insert after the last instructions where the FLAGS register is not yet in use }
  5398. if not GetLastInstruction(p, hp2) then
  5399. asml.InsertBefore(hp1, p)
  5400. else
  5401. asml.InsertAfter(hp1, hp2);
  5402. DebugMsg(SPeepholeOptimization + 'Swapped ' + debug_op2str(taicpu(p).opcode) + ' and mov instructions to improve optimisation potential', hp1);
  5403. for X := 0 to 1 do
  5404. case taicpu(hp1).oper[X]^.typ of
  5405. top_reg:
  5406. AllocRegBetween(taicpu(hp1).oper[X]^.reg, hp1, p, UsedRegs);
  5407. top_ref:
  5408. begin
  5409. if taicpu(hp1).oper[X]^.ref^.base <> NR_NO then
  5410. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.base, hp1, p, UsedRegs);
  5411. if taicpu(hp1).oper[X]^.ref^.index <> NR_NO then
  5412. AllocRegBetween(taicpu(hp1).oper[X]^.ref^.index, hp1, p, UsedRegs);
  5413. end;
  5414. else
  5415. ;
  5416. end;
  5417. end;
  5418. function TX86AsmOptimizer.OptPass2MOV(var p : tai) : boolean;
  5419. function IsXCHGAcceptable: Boolean; inline;
  5420. begin
  5421. { Always accept if optimising for size }
  5422. Result := (cs_opt_size in current_settings.optimizerswitches) or
  5423. (
  5424. {$ifdef x86_64}
  5425. { XCHG takes 3 cycles on AMD Athlon64 }
  5426. (current_settings.optimizecputype >= cpu_core_i)
  5427. {$else x86_64}
  5428. { From the Pentium M onwards, XCHG only has a latency of 2 rather
  5429. than 3, so it becomes a saving compared to three MOVs with two of
  5430. them able to execute simultaneously. [Kit] }
  5431. (current_settings.optimizecputype >= cpu_PentiumM)
  5432. {$endif x86_64}
  5433. );
  5434. end;
  5435. var
  5436. NewRef: TReference;
  5437. hp1, hp2, hp3, hp4: Tai;
  5438. {$ifndef x86_64}
  5439. OperIdx: Integer;
  5440. {$endif x86_64}
  5441. NewInstr : Taicpu;
  5442. NewAligh : Tai_align;
  5443. DestLabel: TAsmLabel;
  5444. begin
  5445. Result:=false;
  5446. { This optimisation adds an instruction, so only do it for speed }
  5447. if not (cs_opt_size in current_settings.optimizerswitches) and
  5448. MatchOpType(taicpu(p), top_const, top_reg) and
  5449. (taicpu(p).oper[0]^.val = 0) then
  5450. begin
  5451. { To avoid compiler warning }
  5452. DestLabel := nil;
  5453. if (p.typ <> ait_instruction) or (taicpu(p).oper[1]^.typ <> top_reg) then
  5454. InternalError(2021040750);
  5455. if not GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[1]^.reg) then
  5456. Exit;
  5457. case hp1.typ of
  5458. ait_label:
  5459. begin
  5460. { Change:
  5461. mov $0,%reg mov $0,%reg
  5462. @Lbl1: @Lbl1:
  5463. test %reg,%reg / cmp $0,%reg test %reg,%reg / mov $0,%reg
  5464. je @Lbl2 jne @Lbl2
  5465. To: To:
  5466. mov $0,%reg mov $0,%reg
  5467. jmp @Lbl2 jmp @Lbl3
  5468. (align) (align)
  5469. @Lbl1: @Lbl1:
  5470. test %reg,%reg / cmp $0,%reg test %reg,%reg / cmp $0,%reg
  5471. je @Lbl2 je @Lbl2
  5472. @Lbl3: <-- Only if label exists
  5473. (Not if it's optimised for size)
  5474. }
  5475. if not GetNextInstruction(hp1, hp2) then
  5476. Exit;
  5477. if not (cs_opt_size in current_settings.optimizerswitches) and
  5478. (hp2.typ = ait_instruction) and
  5479. (
  5480. { Register sizes must exactly match }
  5481. (
  5482. (taicpu(hp2).opcode = A_CMP) and
  5483. MatchOperand(taicpu(hp2).oper[0]^, 0) and
  5484. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  5485. ) or (
  5486. (taicpu(hp2).opcode = A_TEST) and
  5487. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  5488. MatchOperand(taicpu(hp2).oper[1]^, taicpu(p).oper[1]^.reg)
  5489. )
  5490. ) and GetNextInstruction(hp2, hp3) and
  5491. (hp3.typ = ait_instruction) and
  5492. (taicpu(hp3).opcode = A_JCC) and
  5493. (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
  5494. (taicpu(hp3).oper[0]^.ref^.index=NR_NO) and (taicpu(hp3).oper[0]^.ref^.symbol is tasmlabel) then
  5495. begin
  5496. { Check condition of jump }
  5497. { Always true? }
  5498. if condition_in(C_E, taicpu(hp3).condition) then
  5499. begin
  5500. { Copy label symbol and obtain matching label entry for the
  5501. conditional jump, as this will be our destination}
  5502. DestLabel := tasmlabel(taicpu(hp3).oper[0]^.ref^.symbol);
  5503. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Je -> Mov0JmpLblCmp0Je', p);
  5504. Result := True;
  5505. end
  5506. { Always false? }
  5507. else if condition_in(C_NE, taicpu(hp3).condition) and GetNextInstruction(hp3, hp2) then
  5508. begin
  5509. { This is only worth it if there's a jump to take }
  5510. case hp2.typ of
  5511. ait_instruction:
  5512. begin
  5513. if taicpu(hp2).opcode = A_JMP then
  5514. begin
  5515. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  5516. { An unconditional jump follows the conditional jump which will always be false,
  5517. so use this jump's destination for the new jump }
  5518. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with JMP)', p);
  5519. Result := True;
  5520. end
  5521. else if taicpu(hp2).opcode = A_JCC then
  5522. begin
  5523. DestLabel := tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol);
  5524. if condition_in(C_E, taicpu(hp2).condition) then
  5525. begin
  5526. { A second conditional jump follows the conditional jump which will always be false,
  5527. while the second jump is always True, so use this jump's destination for the new jump }
  5528. DebugMsg(SPeepholeOptimization + 'Mov0LblCmp0Jne -> Mov0JmpLblCmp0Jne (with second Jcc)', p);
  5529. Result := True;
  5530. end;
  5531. { Don't risk it if the jump isn't always true (Result remains False) }
  5532. end;
  5533. end;
  5534. else
  5535. { If anything else don't optimise };
  5536. end;
  5537. end;
  5538. if Result then
  5539. begin
  5540. { Just so we have something to insert as a paremeter}
  5541. reference_reset(NewRef, 1, []);
  5542. NewInstr := taicpu.op_ref(A_JMP, S_NO, NewRef);
  5543. { Now actually load the correct parameter }
  5544. NewInstr.loadsymbol(0, DestLabel, 0);
  5545. { Get instruction before original label (may not be p under -O3) }
  5546. if not GetLastInstruction(hp1, hp2) then
  5547. { Shouldn't fail here }
  5548. InternalError(2021040701);
  5549. DestLabel.increfs;
  5550. AsmL.InsertAfter(NewInstr, hp2);
  5551. { Add new alignment field }
  5552. (* AsmL.InsertAfter(
  5553. cai_align.create_max(
  5554. current_settings.alignment.jumpalign,
  5555. current_settings.alignment.jumpalignskipmax
  5556. ),
  5557. NewInstr
  5558. ); *)
  5559. end;
  5560. Exit;
  5561. end;
  5562. end;
  5563. else
  5564. ;
  5565. end;
  5566. end;
  5567. if not GetNextInstruction(p, hp1) then
  5568. Exit;
  5569. if MatchInstruction(hp1, A_JMP, [S_NO]) then
  5570. begin
  5571. { Sometimes the MOVs that OptPass2JMP produces can be improved
  5572. further, but we can't just put this jump optimisation in pass 1
  5573. because it tends to perform worse when conditional jumps are
  5574. nearby (e.g. when converting CMOV instructions). [Kit] }
  5575. if OptPass2JMP(hp1) then
  5576. { call OptPass1MOV once to potentially merge any MOVs that were created }
  5577. Result := OptPass1MOV(p)
  5578. { OptPass2MOV will now exit but will be called again if OptPass1MOV
  5579. returned True and the instruction is still a MOV, thus checking
  5580. the optimisations below }
  5581. { If OptPass2JMP returned False, no optimisations were done to
  5582. the jump and there are no further optimisations that can be done
  5583. to the MOV instruction on this pass }
  5584. end
  5585. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5586. (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  5587. MatchInstruction(hp1,A_ADD,A_SUB,[taicpu(p).opsize]) and
  5588. MatchOpType(taicpu(hp1),top_const,top_reg) and
  5589. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) and
  5590. { be lazy, checking separately for sub would be slightly better }
  5591. (abs(taicpu(hp1).oper[0]^.val)<=$7fffffff) then
  5592. begin
  5593. { Change:
  5594. movl/q %reg1,%reg2 movl/q %reg1,%reg2
  5595. addl/q $x,%reg2 subl/q $x,%reg2
  5596. To:
  5597. leal/q x(%reg1),%reg2 leal/q -x(%reg1),%reg2
  5598. }
  5599. TransferUsedRegs(TmpUsedRegs);
  5600. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5601. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5602. if not GetNextInstruction(hp1, hp2) or
  5603. (
  5604. { The FLAGS register isn't always tracked properly, so do not
  5605. perform this optimisation if a conditional statement follows }
  5606. not RegReadByInstruction(NR_DEFAULTFLAGS, hp2) and
  5607. not RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp2, TmpUsedRegs)
  5608. ) then
  5609. begin
  5610. reference_reset(NewRef, 1, []);
  5611. NewRef.base := taicpu(p).oper[0]^.reg;
  5612. NewRef.scalefactor := 1;
  5613. if taicpu(hp1).opcode = A_ADD then
  5614. begin
  5615. DebugMsg(SPeepholeOptimization + 'MovAdd2Lea', p);
  5616. NewRef.offset := taicpu(hp1).oper[0]^.val;
  5617. end
  5618. else
  5619. begin
  5620. DebugMsg(SPeepholeOptimization + 'MovSub2Lea', p);
  5621. NewRef.offset := -taicpu(hp1).oper[0]^.val;
  5622. end;
  5623. taicpu(p).opcode := A_LEA;
  5624. taicpu(p).loadref(0, NewRef);
  5625. RemoveInstruction(hp1);
  5626. Result := True;
  5627. Exit;
  5628. end;
  5629. end
  5630. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5631. {$ifdef x86_64}
  5632. MatchInstruction(hp1,A_MOVZX,A_MOVSX,A_MOVSXD,[]) and
  5633. {$else x86_64}
  5634. MatchInstruction(hp1,A_MOVZX,A_MOVSX,[]) and
  5635. {$endif x86_64}
  5636. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5637. (taicpu(hp1).oper[0]^.reg = taicpu(p).oper[1]^.reg) then
  5638. { mov reg1, reg2 mov reg1, reg2
  5639. movzx/sx reg2, reg3 to movzx/sx reg1, reg3}
  5640. begin
  5641. taicpu(hp1).oper[0]^.reg := taicpu(p).oper[0]^.reg;
  5642. DebugMsg(SPeepholeOptimization + 'mov %reg1,%reg2; movzx/sx %reg2,%reg3 -> mov %reg1,%reg2;movzx/sx %reg1,%reg3',p);
  5643. { Don't remove the MOV command without first checking that reg2 isn't used afterwards,
  5644. or unless supreg(reg3) = supreg(reg2)). [Kit] }
  5645. TransferUsedRegs(TmpUsedRegs);
  5646. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  5647. if (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) or
  5648. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs)
  5649. then
  5650. begin
  5651. RemoveCurrentP(p, hp1);
  5652. Result:=true;
  5653. end;
  5654. exit;
  5655. end
  5656. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5657. IsXCHGAcceptable and
  5658. { XCHG doesn't support 8-byte registers }
  5659. (taicpu(p).opsize <> S_B) and
  5660. MatchInstruction(hp1, A_MOV, []) and
  5661. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  5662. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[0]^.reg) and
  5663. GetNextInstruction(hp1, hp2) and
  5664. MatchInstruction(hp2, A_MOV, []) and
  5665. { Don't need to call MatchOpType for hp2 because the operand matches below cover for it }
  5666. MatchOperand(taicpu(hp2).oper[0]^, taicpu(p).oper[1]^.reg) and
  5667. MatchOperand(taicpu(hp2).oper[1]^, taicpu(hp1).oper[0]^.reg) then
  5668. begin
  5669. { mov %reg1,%reg2
  5670. mov %reg3,%reg1 -> xchg %reg3,%reg1
  5671. mov %reg2,%reg3
  5672. (%reg2 not used afterwards)
  5673. Note that xchg takes 3 cycles to execute, and generally mov's take
  5674. only one cycle apiece, but the first two mov's can be executed in
  5675. parallel, only taking 2 cycles overall. Older processors should
  5676. therefore only optimise for size. [Kit]
  5677. }
  5678. TransferUsedRegs(TmpUsedRegs);
  5679. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5680. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5681. if not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp2, TmpUsedRegs) then
  5682. begin
  5683. DebugMsg(SPeepholeOptimization + 'MovMovMov2XChg', p);
  5684. AllocRegBetween(taicpu(hp2).oper[1]^.reg, p, hp1, UsedRegs);
  5685. taicpu(hp1).opcode := A_XCHG;
  5686. RemoveCurrentP(p, hp1);
  5687. RemoveInstruction(hp2);
  5688. Result := True;
  5689. Exit;
  5690. end;
  5691. end
  5692. else if MatchOpType(taicpu(p),top_reg,top_reg) and
  5693. MatchInstruction(hp1, A_SAR, []) then
  5694. begin
  5695. if MatchOperand(taicpu(hp1).oper[0]^, 31) then
  5696. begin
  5697. { the use of %edx also covers the opsize being S_L }
  5698. if MatchOperand(taicpu(hp1).oper[1]^, NR_EDX) then
  5699. begin
  5700. { Note it has to be specifically "movl %eax,%edx", and those specific sub-registers }
  5701. if (taicpu(p).oper[0]^.reg = NR_EAX) and
  5702. (taicpu(p).oper[1]^.reg = NR_EDX) then
  5703. begin
  5704. { Change:
  5705. movl %eax,%edx
  5706. sarl $31,%edx
  5707. To:
  5708. cltd
  5709. }
  5710. DebugMsg(SPeepholeOptimization + 'MovSar2Cltd', p);
  5711. RemoveInstruction(hp1);
  5712. taicpu(p).opcode := A_CDQ;
  5713. taicpu(p).opsize := S_NO;
  5714. taicpu(p).clearop(1);
  5715. taicpu(p).clearop(0);
  5716. taicpu(p).ops:=0;
  5717. Result := True;
  5718. end
  5719. else if (cs_opt_size in current_settings.optimizerswitches) and
  5720. (taicpu(p).oper[0]^.reg = NR_EDX) and
  5721. (taicpu(p).oper[1]^.reg = NR_EAX) then
  5722. begin
  5723. { Change:
  5724. movl %edx,%eax
  5725. sarl $31,%edx
  5726. To:
  5727. movl %edx,%eax
  5728. cltd
  5729. Note that this creates a dependency between the two instructions,
  5730. so only perform if optimising for size.
  5731. }
  5732. DebugMsg(SPeepholeOptimization + 'MovSar2MovCltd', p);
  5733. taicpu(hp1).opcode := A_CDQ;
  5734. taicpu(hp1).opsize := S_NO;
  5735. taicpu(hp1).clearop(1);
  5736. taicpu(hp1).clearop(0);
  5737. taicpu(hp1).ops:=0;
  5738. end;
  5739. {$ifndef x86_64}
  5740. end
  5741. { Don't bother if CMOV is supported, because a more optimal
  5742. sequence would have been generated for the Abs() intrinsic }
  5743. else if not(CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype]) and
  5744. { the use of %eax also covers the opsize being S_L }
  5745. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) and
  5746. (taicpu(p).oper[0]^.reg = NR_EAX) and
  5747. (taicpu(p).oper[1]^.reg = NR_EDX) and
  5748. GetNextInstruction(hp1, hp2) and
  5749. MatchInstruction(hp2, A_XOR, [S_L]) and
  5750. MatchOperand(taicpu(hp2).oper[0]^, NR_EAX) and
  5751. MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) and
  5752. GetNextInstruction(hp2, hp3) and
  5753. MatchInstruction(hp3, A_SUB, [S_L]) and
  5754. MatchOperand(taicpu(hp3).oper[0]^, NR_EAX) and
  5755. MatchOperand(taicpu(hp3).oper[1]^, NR_EDX) then
  5756. begin
  5757. { Change:
  5758. movl %eax,%edx
  5759. sarl $31,%eax
  5760. xorl %eax,%edx
  5761. subl %eax,%edx
  5762. (Instruction that uses %edx)
  5763. (%eax deallocated)
  5764. (%edx deallocated)
  5765. To:
  5766. cltd
  5767. xorl %edx,%eax <-- Note the registers have swapped
  5768. subl %edx,%eax
  5769. (Instruction that uses %eax) <-- %eax rather than %edx
  5770. }
  5771. TransferUsedRegs(TmpUsedRegs);
  5772. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  5773. UpdateUsedRegs(TmpUsedRegs, tai(hp1.Next));
  5774. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  5775. if not RegUsedAfterInstruction(NR_EAX, hp3, TmpUsedRegs) then
  5776. begin
  5777. if GetNextInstruction(hp3, hp4) and
  5778. not RegModifiedByInstruction(NR_EDX, hp4) and
  5779. not RegUsedAfterInstruction(NR_EDX, hp4, TmpUsedRegs) then
  5780. begin
  5781. DebugMsg(SPeepholeOptimization + 'abs() intrinsic optimisation', p);
  5782. taicpu(p).opcode := A_CDQ;
  5783. taicpu(p).clearop(1);
  5784. taicpu(p).clearop(0);
  5785. taicpu(p).ops:=0;
  5786. RemoveInstruction(hp1);
  5787. taicpu(hp2).loadreg(0, NR_EDX);
  5788. taicpu(hp2).loadreg(1, NR_EAX);
  5789. taicpu(hp3).loadreg(0, NR_EDX);
  5790. taicpu(hp3).loadreg(1, NR_EAX);
  5791. AllocRegBetween(NR_EAX, hp3, hp4, TmpUsedRegs);
  5792. { Convert references in the following instruction (hp4) from %edx to %eax }
  5793. for OperIdx := 0 to taicpu(hp4).ops - 1 do
  5794. with taicpu(hp4).oper[OperIdx]^ do
  5795. case typ of
  5796. top_reg:
  5797. if getsupreg(reg) = RS_EDX then
  5798. reg := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  5799. top_ref:
  5800. begin
  5801. if getsupreg(reg) = RS_EDX then
  5802. ref^.base := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  5803. if getsupreg(reg) = RS_EDX then
  5804. ref^.index := newreg(R_INTREGISTER,RS_EAX,getsubreg(reg));
  5805. end;
  5806. else
  5807. ;
  5808. end;
  5809. end;
  5810. end;
  5811. {$else x86_64}
  5812. end;
  5813. end
  5814. else if MatchOperand(taicpu(hp1).oper[0]^, 63) and
  5815. { the use of %rdx also covers the opsize being S_Q }
  5816. MatchOperand(taicpu(hp1).oper[1]^, NR_RDX) then
  5817. begin
  5818. { Note it has to be specifically "movq %rax,%rdx", and those specific sub-registers }
  5819. if (taicpu(p).oper[0]^.reg = NR_RAX) and
  5820. (taicpu(p).oper[1]^.reg = NR_RDX) then
  5821. begin
  5822. { Change:
  5823. movq %rax,%rdx
  5824. sarq $63,%rdx
  5825. To:
  5826. cqto
  5827. }
  5828. DebugMsg(SPeepholeOptimization + 'MovSar2Cqto', p);
  5829. RemoveInstruction(hp1);
  5830. taicpu(p).opcode := A_CQO;
  5831. taicpu(p).opsize := S_NO;
  5832. taicpu(p).clearop(1);
  5833. taicpu(p).clearop(0);
  5834. taicpu(p).ops:=0;
  5835. Result := True;
  5836. end
  5837. else if (cs_opt_size in current_settings.optimizerswitches) and
  5838. (taicpu(p).oper[0]^.reg = NR_RDX) and
  5839. (taicpu(p).oper[1]^.reg = NR_RAX) then
  5840. begin
  5841. { Change:
  5842. movq %rdx,%rax
  5843. sarq $63,%rdx
  5844. To:
  5845. movq %rdx,%rax
  5846. cqto
  5847. Note that this creates a dependency between the two instructions,
  5848. so only perform if optimising for size.
  5849. }
  5850. DebugMsg(SPeepholeOptimization + 'MovSar2MovCqto', p);
  5851. taicpu(hp1).opcode := A_CQO;
  5852. taicpu(hp1).opsize := S_NO;
  5853. taicpu(hp1).clearop(1);
  5854. taicpu(hp1).clearop(0);
  5855. taicpu(hp1).ops:=0;
  5856. {$endif x86_64}
  5857. end;
  5858. end;
  5859. end
  5860. else if MatchInstruction(hp1, A_MOV, []) and
  5861. (taicpu(hp1).oper[1]^.typ = top_reg) then
  5862. { Though "GetNextInstruction" could be factored out, along with
  5863. the instructions that depend on hp2, it is an expensive call that
  5864. should be delayed for as long as possible, hence we do cheaper
  5865. checks first that are likely to be False. [Kit] }
  5866. begin
  5867. if (
  5868. (
  5869. MatchOperand(taicpu(p).oper[1]^, NR_EDX) and
  5870. (taicpu(hp1).oper[1]^.reg = NR_EAX) and
  5871. (
  5872. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5873. MatchOperand(taicpu(hp1).oper[0]^, NR_EDX)
  5874. )
  5875. ) or
  5876. (
  5877. MatchOperand(taicpu(p).oper[1]^, NR_EAX) and
  5878. (taicpu(hp1).oper[1]^.reg = NR_EDX) and
  5879. (
  5880. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5881. MatchOperand(taicpu(hp1).oper[0]^, NR_EAX)
  5882. )
  5883. )
  5884. ) and
  5885. GetNextInstruction(hp1, hp2) and
  5886. MatchInstruction(hp2, A_SAR, []) and
  5887. MatchOperand(taicpu(hp2).oper[0]^, 31) then
  5888. begin
  5889. if MatchOperand(taicpu(hp2).oper[1]^, NR_EDX) then
  5890. begin
  5891. { Change:
  5892. movl r/m,%edx movl r/m,%eax movl r/m,%edx movl r/m,%eax
  5893. movl %edx,%eax or movl %eax,%edx or movl r/m,%eax or movl r/m,%edx
  5894. sarl $31,%edx sarl $31,%edx sarl $31,%edx sarl $31,%edx
  5895. To:
  5896. movl r/m,%eax <- Note the change in register
  5897. cltd
  5898. }
  5899. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCltd', p);
  5900. AllocRegBetween(NR_EAX, p, hp1, UsedRegs);
  5901. taicpu(p).loadreg(1, NR_EAX);
  5902. taicpu(hp1).opcode := A_CDQ;
  5903. taicpu(hp1).clearop(1);
  5904. taicpu(hp1).clearop(0);
  5905. taicpu(hp1).ops:=0;
  5906. RemoveInstruction(hp2);
  5907. (*
  5908. {$ifdef x86_64}
  5909. end
  5910. else if MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) and
  5911. { This code sequence does not get generated - however it might become useful
  5912. if and when 128-bit signed integer types make an appearance, so the code
  5913. is kept here for when it is eventually needed. [Kit] }
  5914. (
  5915. (
  5916. (taicpu(hp1).oper[1]^.reg = NR_RAX) and
  5917. (
  5918. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5919. MatchOperand(taicpu(hp1).oper[0]^, NR_RDX)
  5920. )
  5921. ) or
  5922. (
  5923. (taicpu(hp1).oper[1]^.reg = NR_RDX) and
  5924. (
  5925. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^) or
  5926. MatchOperand(taicpu(hp1).oper[0]^, NR_RAX)
  5927. )
  5928. )
  5929. ) and
  5930. GetNextInstruction(hp1, hp2) and
  5931. MatchInstruction(hp2, A_SAR, [S_Q]) and
  5932. MatchOperand(taicpu(hp2).oper[0]^, 63) and
  5933. MatchOperand(taicpu(hp2).oper[1]^, NR_RDX) then
  5934. begin
  5935. { Change:
  5936. movq r/m,%rdx movq r/m,%rax movq r/m,%rdx movq r/m,%rax
  5937. movq %rdx,%rax or movq %rax,%rdx or movq r/m,%rax or movq r/m,%rdx
  5938. sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx sarq $63,%rdx
  5939. To:
  5940. movq r/m,%rax <- Note the change in register
  5941. cqto
  5942. }
  5943. DebugMsg(SPeepholeOptimization + 'MovMovSar2MovCqto', p);
  5944. AllocRegBetween(NR_RAX, p, hp1, UsedRegs);
  5945. taicpu(p).loadreg(1, NR_RAX);
  5946. taicpu(hp1).opcode := A_CQO;
  5947. taicpu(hp1).clearop(1);
  5948. taicpu(hp1).clearop(0);
  5949. taicpu(hp1).ops:=0;
  5950. RemoveInstruction(hp2);
  5951. {$endif x86_64}
  5952. *)
  5953. end;
  5954. end;
  5955. {$ifdef x86_64}
  5956. end
  5957. else if (taicpu(p).opsize = S_L) and
  5958. (taicpu(p).oper[1]^.typ = top_reg) and
  5959. (
  5960. MatchInstruction(hp1, A_MOV,[]) and
  5961. (taicpu(hp1).opsize = S_L) and
  5962. (taicpu(hp1).oper[1]^.typ = top_reg)
  5963. ) and (
  5964. GetNextInstruction(hp1, hp2) and
  5965. (tai(hp2).typ=ait_instruction) and
  5966. (taicpu(hp2).opsize = S_Q) and
  5967. (
  5968. (
  5969. MatchInstruction(hp2, A_ADD,[]) and
  5970. (taicpu(hp2).opsize = S_Q) and
  5971. (taicpu(hp2).oper[0]^.typ = top_reg) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  5972. (
  5973. (
  5974. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(p).oper[1]^.reg)) and
  5975. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  5976. ) or (
  5977. (getsupreg(taicpu(hp2).oper[0]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5978. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  5979. )
  5980. )
  5981. ) or (
  5982. MatchInstruction(hp2, A_LEA,[]) and
  5983. (taicpu(hp2).oper[0]^.ref^.offset = 0) and
  5984. (taicpu(hp2).oper[0]^.ref^.scalefactor <= 1) and
  5985. (
  5986. (
  5987. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(p).oper[1]^.reg)) and
  5988. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(hp1).oper[1]^.reg))
  5989. ) or (
  5990. (getsupreg(taicpu(hp2).oper[0]^.ref^.base) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  5991. (getsupreg(taicpu(hp2).oper[0]^.ref^.index) = getsupreg(taicpu(p).oper[1]^.reg))
  5992. )
  5993. ) and (
  5994. (
  5995. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg))
  5996. ) or (
  5997. (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(p).oper[1]^.reg))
  5998. )
  5999. )
  6000. )
  6001. )
  6002. ) and (
  6003. GetNextInstruction(hp2, hp3) and
  6004. MatchInstruction(hp3, A_SHR,[]) and
  6005. (taicpu(hp3).opsize = S_Q) and
  6006. (taicpu(hp3).oper[0]^.typ = top_const) and (taicpu(hp2).oper[1]^.typ = top_reg) and
  6007. (taicpu(hp3).oper[0]^.val = 1) and
  6008. (taicpu(hp3).oper[1]^.reg = taicpu(hp2).oper[1]^.reg)
  6009. ) then
  6010. begin
  6011. { Change movl x, reg1d movl x, reg1d
  6012. movl y, reg2d movl y, reg2d
  6013. addq reg2q,reg1q or leaq (reg1q,reg2q),reg1q
  6014. shrq $1, reg1q shrq $1, reg1q
  6015. ( reg1d and reg2d can be switched around in the first two instructions )
  6016. To movl x, reg1d
  6017. addl y, reg1d
  6018. rcrl $1, reg1d
  6019. This corresponds to the common expression (x + y) shr 1, where
  6020. x and y are Cardinals (replacing "shr 1" with "div 2" produces
  6021. smaller code, but won't account for x + y causing an overflow). [Kit]
  6022. }
  6023. if (getsupreg(taicpu(hp2).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) then
  6024. { Change first MOV command to have the same register as the final output }
  6025. taicpu(p).oper[1]^.reg := taicpu(hp1).oper[1]^.reg
  6026. else
  6027. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[1]^.reg;
  6028. { Change second MOV command to an ADD command. This is easier than
  6029. converting the existing command because it means we don't have to
  6030. touch 'y', which might be a complicated reference, and also the
  6031. fact that the third command might either be ADD or LEA. [Kit] }
  6032. taicpu(hp1).opcode := A_ADD;
  6033. { Delete old ADD/LEA instruction }
  6034. RemoveInstruction(hp2);
  6035. { Convert "shrq $1, reg1q" to "rcr $1, reg1d" }
  6036. taicpu(hp3).opcode := A_RCR;
  6037. taicpu(hp3).changeopsize(S_L);
  6038. setsubreg(taicpu(hp3).oper[1]^.reg, R_SUBD);
  6039. {$endif x86_64}
  6040. end;
  6041. end;
  6042. function TX86AsmOptimizer.OptPass2Movx(var p : tai) : boolean;
  6043. var
  6044. ThisReg: TRegister;
  6045. MinSize, MaxSize, TrySmaller, TargetSize: TOpSize;
  6046. TargetSubReg: TSubRegister;
  6047. hp1, hp2: tai;
  6048. RegInUse, RegChanged, p_removed: Boolean;
  6049. { Store list of found instructions so we don't have to call
  6050. GetNextInstructionUsingReg multiple times }
  6051. InstrList: array of taicpu;
  6052. InstrMax, Index: Integer;
  6053. UpperLimit, TrySmallerLimit: TCgInt;
  6054. PreMessage: string;
  6055. { Data flow analysis }
  6056. TestValMin, TestValMax: TCgInt;
  6057. SmallerOverflow: Boolean;
  6058. begin
  6059. Result := False;
  6060. p_removed := False;
  6061. { This is anything but quick! }
  6062. if not(cs_opt_level2 in current_settings.optimizerswitches) then
  6063. Exit;
  6064. SetLength(InstrList, 0);
  6065. InstrMax := -1;
  6066. ThisReg := taicpu(p).oper[1]^.reg;
  6067. case taicpu(p).opsize of
  6068. S_BW, S_BL:
  6069. begin
  6070. {$if defined(i386) or defined(i8086)}
  6071. { If the target size is 8-bit, make sure we can actually encode it }
  6072. if not (GetSupReg(ThisReg) in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) then
  6073. Exit;
  6074. {$endif i386 or i8086}
  6075. UpperLimit := $FF;
  6076. MinSize := S_B;
  6077. if taicpu(p).opsize = S_BW then
  6078. MaxSize := S_W
  6079. else
  6080. MaxSize := S_L;
  6081. end;
  6082. S_WL:
  6083. begin
  6084. UpperLimit := $FFFF;
  6085. MinSize := S_W;
  6086. MaxSize := S_L;
  6087. end
  6088. else
  6089. InternalError(2020112301);
  6090. end;
  6091. TestValMin := 0;
  6092. TestValMax := UpperLimit;
  6093. TrySmallerLimit := UpperLimit;
  6094. TrySmaller := S_NO;
  6095. SmallerOverflow := False;
  6096. RegChanged := False;
  6097. hp1 := p;
  6098. while GetNextInstructionUsingReg(hp1, hp1, ThisReg) and
  6099. (hp1.typ = ait_instruction) and
  6100. (
  6101. { Under -O1 and -O2, GetNextInstructionUsingReg may return an
  6102. instruction that doesn't actually contain ThisReg }
  6103. (cs_opt_level3 in current_settings.optimizerswitches) or
  6104. RegInInstruction(ThisReg, hp1)
  6105. ) do
  6106. begin
  6107. case taicpu(hp1).opcode of
  6108. A_INC,A_DEC:
  6109. begin
  6110. { Has to be an exact match on the register }
  6111. if not MatchOperand(taicpu(hp1).oper[0]^, ThisReg) then
  6112. Break;
  6113. if taicpu(hp1).opcode = A_INC then
  6114. begin
  6115. Inc(TestValMin);
  6116. Inc(TestValMax);
  6117. end
  6118. else
  6119. begin
  6120. Dec(TestValMin);
  6121. Dec(TestValMax);
  6122. end;
  6123. end;
  6124. A_CMP:
  6125. begin
  6126. if (taicpu(hp1).oper[1]^.typ <> top_reg) or
  6127. { Has to be an exact match on the register }
  6128. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6129. (taicpu(hp1).oper[0]^.typ <> top_const) or
  6130. { Make sure the comparison value is not smaller than the
  6131. smallest allowed signed value for the minimum size (e.g.
  6132. -128 for 8-bit) }
  6133. not (
  6134. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6135. { Is it in the negative range? }
  6136. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  6137. ) then
  6138. Break;
  6139. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  6140. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  6141. if (TestValMin < TrySmallerLimit) or (TestValMax < TrySmallerLimit) or
  6142. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  6143. { Overflow }
  6144. Break;
  6145. { Check to see if the active register is used afterwards }
  6146. TransferUsedRegs(TmpUsedRegs);
  6147. IncludeRegInUsedRegs(ThisReg, TmpUsedRegs);
  6148. if not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  6149. begin
  6150. case MinSize of
  6151. S_B:
  6152. TargetSubReg := R_SUBL;
  6153. S_W:
  6154. TargetSubReg := R_SUBW;
  6155. else
  6156. InternalError(2021051002);
  6157. end;
  6158. { Update the register to its new size }
  6159. setsubreg(ThisReg, TargetSubReg);
  6160. taicpu(hp1).oper[1]^.reg := ThisReg;
  6161. taicpu(hp1).opsize := MinSize;
  6162. { Convert the input MOVZX to a MOV }
  6163. if (taicpu(p).oper[0]^.typ = top_reg) and
  6164. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  6165. begin
  6166. { Or remove it completely! }
  6167. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1a', p);
  6168. RemoveCurrentP(p);
  6169. p_removed := True;
  6170. end
  6171. else
  6172. begin
  6173. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1a', p);
  6174. taicpu(p).opcode := A_MOV;
  6175. taicpu(p).oper[1]^.reg := ThisReg;
  6176. taicpu(p).opsize := MinSize;
  6177. end;
  6178. if (InstrMax >= 0) then
  6179. begin
  6180. for Index := 0 to InstrMax do
  6181. begin
  6182. { If p_removed is true, then the original MOV/Z was removed
  6183. and removing the AND instruction may not be safe if it
  6184. appears first }
  6185. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  6186. InternalError(2020112311);
  6187. if InstrList[Index].oper[0]^.typ = top_reg then
  6188. InstrList[Index].oper[0]^.reg := ThisReg;
  6189. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  6190. InstrList[Index].opsize := MinSize;
  6191. end;
  6192. end;
  6193. Result := True;
  6194. Exit;
  6195. end;
  6196. end;
  6197. { OR and XOR are not included because they can too easily fool
  6198. the data flow analysis (they can cause non-linear behaviour) }
  6199. A_ADD,A_SUB,A_AND,A_SHL,A_SHR:
  6200. begin
  6201. if
  6202. (taicpu(hp1).oper[1]^.typ <> top_reg) or
  6203. { Has to be an exact match on the register }
  6204. (taicpu(hp1).oper[1]^.reg <> ThisReg) or not
  6205. (
  6206. (
  6207. (taicpu(hp1).oper[0]^.typ = top_const) and
  6208. (
  6209. (
  6210. (taicpu(hp1).opcode = A_SHL) and
  6211. (
  6212. ((MinSize = S_B) and (taicpu(hp1).oper[0]^.val < 8)) or
  6213. ((MinSize = S_W) and (taicpu(hp1).oper[0]^.val < 16)) or
  6214. ((MinSize = S_L) and (taicpu(hp1).oper[0]^.val < 32))
  6215. )
  6216. ) or (
  6217. (taicpu(hp1).opcode <> A_SHL) and
  6218. (
  6219. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6220. { Is it in the negative range? }
  6221. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val))
  6222. )
  6223. )
  6224. )
  6225. ) or (
  6226. MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^.reg) and
  6227. ((taicpu(hp1).opcode = A_ADD) or (taicpu(hp1).opcode = A_AND) or (taicpu(hp1).opcode = A_SUB))
  6228. )
  6229. ) then
  6230. Break;
  6231. case taicpu(hp1).opcode of
  6232. A_ADD:
  6233. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  6234. begin
  6235. TestValMin := TestValMin * 2;
  6236. TestValMax := TestValMax * 2;
  6237. end
  6238. else
  6239. begin
  6240. TestValMin := TestValMin + taicpu(hp1).oper[0]^.val;
  6241. TestValMax := TestValMax + taicpu(hp1).oper[0]^.val;
  6242. end;
  6243. A_SUB:
  6244. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  6245. begin
  6246. TestValMin := 0;
  6247. TestValMax := 0;
  6248. end
  6249. else
  6250. begin
  6251. TestValMin := TestValMin - taicpu(hp1).oper[0]^.val;
  6252. TestValMax := TestValMax - taicpu(hp1).oper[0]^.val;
  6253. end;
  6254. A_AND:
  6255. if (taicpu(hp1).oper[0]^.typ = top_const) then
  6256. begin
  6257. { we might be able to go smaller if AND appears first }
  6258. if InstrMax = -1 then
  6259. case MinSize of
  6260. S_B:
  6261. ;
  6262. S_W:
  6263. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  6264. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  6265. begin
  6266. TrySmaller := S_B;
  6267. TrySmallerLimit := $FF;
  6268. end;
  6269. S_L:
  6270. if ((taicpu(hp1).oper[0]^.val and $FF) = taicpu(hp1).oper[0]^.val) or
  6271. ((not(taicpu(hp1).oper[0]^.val) and $7F) = (not taicpu(hp1).oper[0]^.val)) then
  6272. begin
  6273. TrySmaller := S_B;
  6274. TrySmallerLimit := $FF;
  6275. end
  6276. else if ((taicpu(hp1).oper[0]^.val and $FFFF) = taicpu(hp1).oper[0]^.val) or
  6277. ((not(taicpu(hp1).oper[0]^.val) and $7FFF) = (not taicpu(hp1).oper[0]^.val)) then
  6278. begin
  6279. TrySmaller := S_W;
  6280. TrySmallerLimit := $FFFF;
  6281. end;
  6282. else
  6283. InternalError(2020112320);
  6284. end;
  6285. TestValMin := TestValMin and taicpu(hp1).oper[0]^.val;
  6286. TestValMax := TestValMax and taicpu(hp1).oper[0]^.val;
  6287. end;
  6288. A_SHL:
  6289. begin
  6290. TestValMin := TestValMin shl taicpu(hp1).oper[0]^.val;
  6291. TestValMax := TestValMax shl taicpu(hp1).oper[0]^.val;
  6292. end;
  6293. A_SHR:
  6294. begin
  6295. { we might be able to go smaller if SHR appears first }
  6296. if InstrMax = -1 then
  6297. case MinSize of
  6298. S_B:
  6299. ;
  6300. S_W:
  6301. if (taicpu(hp1).oper[0]^.val >= 8) then
  6302. begin
  6303. TrySmaller := S_B;
  6304. TrySmallerLimit := $FF;
  6305. end;
  6306. S_L:
  6307. if (taicpu(hp1).oper[0]^.val >= 24) then
  6308. begin
  6309. TrySmaller := S_B;
  6310. TrySmallerLimit := $FF;
  6311. end
  6312. else if (taicpu(hp1).oper[0]^.val >= 16) then
  6313. begin
  6314. TrySmaller := S_W;
  6315. TrySmallerLimit := $FFFF;
  6316. end;
  6317. else
  6318. InternalError(2020112321);
  6319. end;
  6320. TestValMin := TestValMin shr taicpu(hp1).oper[0]^.val;
  6321. TestValMax := TestValMax shr taicpu(hp1).oper[0]^.val;
  6322. end;
  6323. else
  6324. InternalError(2020112303);
  6325. end;
  6326. end;
  6327. (*
  6328. A_IMUL:
  6329. case taicpu(hp1).ops of
  6330. 2:
  6331. begin
  6332. if not MatchOpType(hp1, top_reg, top_reg) or
  6333. { Has to be an exact match on the register }
  6334. (taicpu(hp1).oper[0]^.reg <> ThisReg) or
  6335. (taicpu(hp1).oper[1]^.reg <> ThisReg) then
  6336. Break;
  6337. TestValMin := TestValMin * TestValMin;
  6338. TestValMax := TestValMax * TestValMax;
  6339. end;
  6340. 3:
  6341. begin
  6342. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  6343. { Has to be an exact match on the register }
  6344. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6345. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  6346. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6347. { Is it in the negative range? }
  6348. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  6349. Break;
  6350. TestValMin := TestValMin * taicpu(hp1).oper[0]^.val;
  6351. TestValMax := TestValMax * taicpu(hp1).oper[0]^.val;
  6352. end;
  6353. else
  6354. Break;
  6355. end;
  6356. A_IDIV:
  6357. case taicpu(hp1).ops of
  6358. 3:
  6359. begin
  6360. if not MatchOpType(hp1, top_const, top_reg, top_reg) or
  6361. { Has to be an exact match on the register }
  6362. (taicpu(hp1).oper[1]^.reg <> ThisReg) or
  6363. (taicpu(hp1).oper[2]^.reg <> ThisReg) or
  6364. ((taicpu(hp1).oper[0]^.val and UpperLimit) = taicpu(hp1).oper[0]^.val) or
  6365. { Is it in the negative range? }
  6366. (((not taicpu(hp1).oper[0]^.val) and (UpperLimit shr 1)) = (not taicpu(hp1).oper[0]^.val)) then
  6367. Break;
  6368. TestValMin := TestValMin div taicpu(hp1).oper[0]^.val;
  6369. TestValMax := TestValMax div taicpu(hp1).oper[0]^.val;
  6370. end;
  6371. else
  6372. Break;
  6373. end;
  6374. *)
  6375. A_MOVZX:
  6376. begin
  6377. if not MatchOpType(taicpu(hp1), top_reg, top_reg) then
  6378. Break;
  6379. if not SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, ThisReg) then
  6380. begin
  6381. { Because hp1 was obtained via GetNextInstructionUsingReg
  6382. and ThisReg doesn't appear in the first operand, it
  6383. must appear in the second operand and hence gets
  6384. overwritten }
  6385. if (InstrMax = -1) and
  6386. Reg1WriteOverwritesReg2Entirely(taicpu(hp1).oper[1]^.reg, ThisReg) then
  6387. begin
  6388. { The two MOVZX instructions are adjacent, so remove the first one }
  6389. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 5', p);
  6390. RemoveCurrentP(p);
  6391. Result := True;
  6392. Exit;
  6393. end;
  6394. Break;
  6395. end;
  6396. { The objective here is to try to find a combination that
  6397. removes one of the MOV/Z instructions. }
  6398. case taicpu(hp1).opsize of
  6399. S_WL:
  6400. if (MinSize in [S_B, S_W]) then
  6401. begin
  6402. TargetSize := S_L;
  6403. TargetSubReg := R_SUBD;
  6404. end
  6405. else if ((TrySmaller in [S_B, S_W]) and not SmallerOverflow) then
  6406. begin
  6407. TargetSize := TrySmaller;
  6408. if TrySmaller = S_B then
  6409. TargetSubReg := R_SUBL
  6410. else
  6411. TargetSubReg := R_SUBW;
  6412. end
  6413. else
  6414. Break;
  6415. S_BW:
  6416. if (MinSize in [S_B, S_W]) then
  6417. begin
  6418. TargetSize := S_W;
  6419. TargetSubReg := R_SUBW;
  6420. end
  6421. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  6422. begin
  6423. TargetSize := S_B;
  6424. TargetSubReg := R_SUBL;
  6425. end
  6426. else
  6427. Break;
  6428. S_BL:
  6429. if (MinSize in [S_B, S_W]) then
  6430. begin
  6431. TargetSize := S_L;
  6432. TargetSubReg := R_SUBD;
  6433. end
  6434. else if ((TrySmaller = S_B) and not SmallerOverflow) then
  6435. begin
  6436. TargetSize := S_B;
  6437. TargetSubReg := R_SUBL;
  6438. end
  6439. else
  6440. Break;
  6441. else
  6442. InternalError(2020112302);
  6443. end;
  6444. { Update the register to its new size }
  6445. setsubreg(ThisReg, TargetSubReg);
  6446. if TargetSize = MinSize then
  6447. begin
  6448. { Convert the input MOVZX to a MOV }
  6449. if (taicpu(p).oper[0]^.typ = top_reg) and
  6450. SuperRegistersEqual(taicpu(p).oper[0]^.reg, ThisReg) then
  6451. begin
  6452. { Or remove it completely! }
  6453. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 1', p);
  6454. RemoveCurrentP(p);
  6455. p_removed := True;
  6456. end
  6457. else
  6458. begin
  6459. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 1', p);
  6460. taicpu(p).opcode := A_MOV;
  6461. taicpu(p).oper[1]^.reg := ThisReg;
  6462. taicpu(p).opsize := TargetSize;
  6463. end;
  6464. Result := True;
  6465. end
  6466. else if TargetSize <> MaxSize then
  6467. begin
  6468. case MaxSize of
  6469. S_L:
  6470. if TargetSize = S_W then
  6471. begin
  6472. DebugMsg(SPeepholeOptimization + 'movzbl2movzbw', p);
  6473. taicpu(p).opsize := S_BW;
  6474. taicpu(p).oper[1]^.reg := ThisReg;
  6475. Result := True;
  6476. end
  6477. else
  6478. InternalError(2020112341);
  6479. S_W:
  6480. if TargetSize = S_L then
  6481. begin
  6482. DebugMsg(SPeepholeOptimization + 'movzbw2movzbl', p);
  6483. taicpu(p).opsize := S_BL;
  6484. taicpu(p).oper[1]^.reg := ThisReg;
  6485. Result := True;
  6486. end
  6487. else
  6488. InternalError(2020112342);
  6489. else
  6490. ;
  6491. end;
  6492. end;
  6493. if (MaxSize = TargetSize) or
  6494. ((TargetSize = S_L) and (taicpu(hp1).opsize in [S_L, S_BL, S_WL])) or
  6495. ((TargetSize = S_W) and (taicpu(hp1).opsize in [S_W, S_BW])) then
  6496. begin
  6497. { Convert the output MOVZX to a MOV }
  6498. if SuperRegistersEqual(taicpu(hp1).oper[1]^.reg, ThisReg) then
  6499. begin
  6500. { Or remove it completely! }
  6501. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 2', hp1);
  6502. { Be careful; if p = hp1 and p was also removed, p
  6503. will become a dangling pointer }
  6504. if p = hp1 then
  6505. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  6506. else
  6507. RemoveInstruction(hp1);
  6508. end
  6509. else
  6510. begin
  6511. taicpu(hp1).opcode := A_MOV;
  6512. taicpu(hp1).oper[0]^.reg := ThisReg;
  6513. taicpu(hp1).opsize := TargetSize;
  6514. { Check to see if the active register is used afterwards;
  6515. if not, we can change it and make a saving. }
  6516. RegInUse := False;
  6517. TransferUsedRegs(TmpUsedRegs);
  6518. { The target register may be marked as in use to cross
  6519. a jump to a distant label, so exclude it }
  6520. ExcludeRegFromUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs);
  6521. hp2 := p;
  6522. repeat
  6523. UpdateUsedRegs(TmpUsedRegs, tai(hp2.next));
  6524. { Explicitly check for the excluded register (don't include the first
  6525. instruction as it may be reading from here }
  6526. if ((p <> hp2) and (RegInInstruction(taicpu(hp1).oper[1]^.reg, hp2))) or
  6527. RegInUsedRegs(taicpu(hp1).oper[1]^.reg, TmpUsedRegs) then
  6528. begin
  6529. RegInUse := True;
  6530. Break;
  6531. end;
  6532. if not GetNextInstruction(hp2, hp2) then
  6533. InternalError(2020112340);
  6534. until (hp2 = hp1);
  6535. if not RegInUse and not RegUsedAfterInstruction(ThisReg, hp1, TmpUsedRegs) then
  6536. begin
  6537. DebugMsg(SPeepholeOptimization + 'Simplified register usage so ' + debug_regname(taicpu(hp1).oper[1]^.reg) + ' = ' + debug_regname(taicpu(p).oper[1]^.reg), p);
  6538. ThisReg := taicpu(hp1).oper[1]^.reg;
  6539. RegChanged := True;
  6540. TransferUsedRegs(TmpUsedRegs);
  6541. AllocRegBetween(ThisReg, p, hp1, TmpUsedRegs);
  6542. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 3', hp1);
  6543. if p = hp1 then
  6544. RemoveCurrentp(p) { p = hp1 and will then become the next instruction }
  6545. else
  6546. RemoveInstruction(hp1);
  6547. { Instruction will become "mov %reg,%reg" }
  6548. if not p_removed and (taicpu(p).opcode = A_MOV) and
  6549. MatchOperand(taicpu(p).oper[0]^, ThisReg) then
  6550. begin
  6551. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 6', p);
  6552. RemoveCurrentP(p);
  6553. p_removed := True;
  6554. end
  6555. else
  6556. taicpu(p).oper[1]^.reg := ThisReg;
  6557. Result := True;
  6558. end
  6559. else
  6560. DebugMsg(SPeepholeOptimization + 'Movzx2Mov 2', hp1);
  6561. end;
  6562. end
  6563. else
  6564. InternalError(2020112330);
  6565. { Now go through every instruction we found and change the
  6566. size. If TargetSize = MaxSize, then almost no changes are
  6567. needed and Result can remain False if it hasn't been set
  6568. yet.
  6569. If RegChanged is True, then the register requires changing
  6570. and so the point about TargetSize = MaxSize doesn't apply. }
  6571. if ((TargetSize <> MaxSize) or RegChanged) and (InstrMax >= 0) then
  6572. begin
  6573. for Index := 0 to InstrMax do
  6574. begin
  6575. { If p_removed is true, then the original MOV/Z was removed
  6576. and removing the AND instruction may not be safe if it
  6577. appears first }
  6578. if (InstrList[Index].oper[InstrList[Index].ops - 1]^.typ <> top_reg) then
  6579. InternalError(2020112310);
  6580. if InstrList[Index].oper[0]^.typ = top_reg then
  6581. InstrList[Index].oper[0]^.reg := ThisReg;
  6582. InstrList[Index].oper[InstrList[Index].ops - 1]^.reg := ThisReg;
  6583. InstrList[Index].opsize := TargetSize;
  6584. end;
  6585. Result := True;
  6586. end;
  6587. Exit;
  6588. end;
  6589. else
  6590. { This includes ADC, SBB, IDIV and SAR }
  6591. Break;
  6592. end;
  6593. if (TestValMin < 0) or (TestValMax < 0) or
  6594. (TestValMin > UpperLimit) or (TestValMax > UpperLimit) then
  6595. { Overflow }
  6596. Break
  6597. else if not SmallerOverflow and (TrySmaller <> S_NO) and
  6598. ((TestValMin > TrySmallerLimit) or (TestValMax > TrySmallerLimit)) then
  6599. SmallerOverflow := True;
  6600. { Contains highest index (so instruction count - 1) }
  6601. Inc(InstrMax);
  6602. if InstrMax > High(InstrList) then
  6603. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  6604. InstrList[InstrMax] := taicpu(hp1);
  6605. end;
  6606. end;
  6607. function TX86AsmOptimizer.OptPass2Imul(var p : tai) : boolean;
  6608. var
  6609. hp1 : tai;
  6610. begin
  6611. Result:=false;
  6612. if (taicpu(p).ops >= 2) and
  6613. ((taicpu(p).oper[0]^.typ = top_const) or
  6614. ((taicpu(p).oper[0]^.typ = top_ref) and (taicpu(p).oper[0]^.ref^.refaddr=addr_full))) and
  6615. (taicpu(p).oper[1]^.typ = top_reg) and
  6616. ((taicpu(p).ops = 2) or
  6617. ((taicpu(p).oper[2]^.typ = top_reg) and
  6618. (taicpu(p).oper[2]^.reg = taicpu(p).oper[1]^.reg))) and
  6619. GetLastInstruction(p,hp1) and
  6620. MatchInstruction(hp1,A_MOV,[]) and
  6621. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6622. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  6623. begin
  6624. TransferUsedRegs(TmpUsedRegs);
  6625. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,p,TmpUsedRegs)) or
  6626. ((taicpu(p).ops = 3) and (taicpu(p).oper[1]^.reg=taicpu(p).oper[2]^.reg)) then
  6627. { change
  6628. mov reg1,reg2
  6629. imul y,reg2 to imul y,reg1,reg2 }
  6630. begin
  6631. taicpu(p).ops := 3;
  6632. taicpu(p).loadreg(2,taicpu(p).oper[1]^.reg);
  6633. taicpu(p).loadreg(1,taicpu(hp1).oper[0]^.reg);
  6634. DebugMsg(SPeepholeOptimization + 'MovImul2Imul done',p);
  6635. RemoveInstruction(hp1);
  6636. result:=true;
  6637. end;
  6638. end;
  6639. end;
  6640. procedure TX86AsmOptimizer.ConvertJumpToRET(const p: tai; const ret_p: tai);
  6641. var
  6642. ThisLabel: TAsmLabel;
  6643. begin
  6644. ThisLabel := tasmlabel(taicpu(p).oper[0]^.ref^.symbol);
  6645. ThisLabel.decrefs;
  6646. taicpu(p).opcode := A_RET;
  6647. taicpu(p).is_jmp := false;
  6648. taicpu(p).ops := taicpu(ret_p).ops;
  6649. case taicpu(ret_p).ops of
  6650. 0:
  6651. taicpu(p).clearop(0);
  6652. 1:
  6653. taicpu(p).loadconst(0,taicpu(ret_p).oper[0]^.val);
  6654. else
  6655. internalerror(2016041301);
  6656. end;
  6657. { If the original label is now dead, it might turn out that the label
  6658. immediately follows p. As a result, everything beyond it, which will
  6659. be just some final register configuration and a RET instruction, is
  6660. now dead code. [Kit] }
  6661. { NOTE: This is much faster than introducing a OptPass2RET routine and
  6662. running RemoveDeadCodeAfterJump for each RET instruction, because
  6663. this optimisation rarely happens and most RETs appear at the end of
  6664. routines where there is nothing that can be stripped. [Kit] }
  6665. if not ThisLabel.is_used then
  6666. RemoveDeadCodeAfterJump(p);
  6667. end;
  6668. function TX86AsmOptimizer.OptPass2SETcc(var p: tai): boolean;
  6669. var
  6670. hp1,hp2,next: tai; SetC, JumpC: TAsmCond;
  6671. Unconditional, PotentialModified: Boolean;
  6672. OperPtr: POper;
  6673. NewRef: TReference;
  6674. InstrList: array of taicpu;
  6675. InstrMax, Index: Integer;
  6676. const
  6677. {$ifdef DEBUG_AOPTCPU}
  6678. SNoFlags: shortstring = ' so the flags aren''t modified';
  6679. {$else DEBUG_AOPTCPU}
  6680. SNoFlags = '';
  6681. {$endif DEBUG_AOPTCPU}
  6682. begin
  6683. Result:=false;
  6684. if MatchOpType(taicpu(p),top_reg) and GetNextInstructionUsingReg(p, hp1, taicpu(p).oper[0]^.reg) then
  6685. begin
  6686. if MatchInstruction(hp1, A_TEST, [S_B]) and
  6687. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  6688. (taicpu(hp1).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  6689. (taicpu(p).oper[0]^.reg = taicpu(hp1).oper[1]^.reg) and
  6690. GetNextInstruction(hp1, hp2) and
  6691. MatchInstruction(hp2, A_Jcc, A_SETcc, []) then
  6692. { Change from: To:
  6693. set(C) %reg j(~C) label
  6694. test %reg,%reg/cmp $0,%reg
  6695. je label
  6696. set(C) %reg j(C) label
  6697. test %reg,%reg/cmp $0,%reg
  6698. jne label
  6699. (Also do something similar with sete/setne instead of je/jne)
  6700. }
  6701. begin
  6702. { Before we do anything else, we need to check the instructions
  6703. in between SETcc and TEST to make sure they don't modify the
  6704. FLAGS register - if -O2 or under, there won't be any
  6705. instructions between SET and TEST }
  6706. TransferUsedRegs(TmpUsedRegs);
  6707. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  6708. if (cs_opt_level3 in current_settings.optimizerswitches) then
  6709. begin
  6710. next := p;
  6711. SetLength(InstrList, 0);
  6712. InstrMax := -1;
  6713. PotentialModified := False;
  6714. { Make a note of every instruction that modifies the FLAGS
  6715. register }
  6716. while GetNextInstruction(next, next) and (next <> hp1) do
  6717. begin
  6718. if next.typ <> ait_instruction then
  6719. { GetNextInstructionUsingReg should have returned False }
  6720. InternalError(2021051701);
  6721. if RegModifiedByInstruction(NR_DEFAULTFLAGS, next) then
  6722. begin
  6723. case taicpu(next).opcode of
  6724. A_SETcc,
  6725. A_CMOVcc,
  6726. A_Jcc:
  6727. begin
  6728. if PotentialModified then
  6729. { Not safe because the flags were modified earlier }
  6730. Exit
  6731. else
  6732. { Condition is the same as the initial SETcc, so this is safe
  6733. (don't add to instruction list though) }
  6734. Continue;
  6735. end;
  6736. A_ADD:
  6737. begin
  6738. if (taicpu(next).opsize = S_B) or
  6739. { LEA doesn't support 8-bit operands }
  6740. (taicpu(next).oper[1]^.typ <> top_reg) or
  6741. { Must write to a register }
  6742. (taicpu(next).oper[0]^.typ = top_ref) then
  6743. { Require a constant or a register }
  6744. Exit;
  6745. PotentialModified := True;
  6746. end;
  6747. A_SUB:
  6748. begin
  6749. if (taicpu(next).opsize = S_B) or
  6750. { LEA doesn't support 8-bit operands }
  6751. (taicpu(next).oper[1]^.typ <> top_reg) or
  6752. { Must write to a register }
  6753. (taicpu(next).oper[0]^.typ <> top_const) or
  6754. (taicpu(next).oper[0]^.val = $80000000) then
  6755. { Can't subtract a register with LEA - also
  6756. check that the value isn't -2^31, as this
  6757. can't be negated }
  6758. Exit;
  6759. PotentialModified := True;
  6760. end;
  6761. A_SAL,
  6762. A_SHL:
  6763. begin
  6764. if (taicpu(next).opsize = S_B) or
  6765. { LEA doesn't support 8-bit operands }
  6766. (taicpu(next).oper[1]^.typ <> top_reg) or
  6767. { Must write to a register }
  6768. (taicpu(next).oper[0]^.typ <> top_const) or
  6769. (taicpu(next).oper[0]^.val < 0) or
  6770. (taicpu(next).oper[0]^.val > 3) then
  6771. Exit;
  6772. PotentialModified := True;
  6773. end;
  6774. A_IMUL:
  6775. begin
  6776. if (taicpu(next).ops <> 3) or
  6777. (taicpu(next).oper[1]^.typ <> top_reg) or
  6778. { Must write to a register }
  6779. (taicpu(next).oper[2]^.val in [2,3,4,5,8,9]) then
  6780. { We can convert "imul x,%reg1,%reg2" (where x = 2, 4 or 8)
  6781. to "lea (%reg1,x),%reg2". If x = 3, 5 or 9, we can
  6782. change this to "lea (%reg1,%reg1,(x-1)),%reg2" }
  6783. Exit
  6784. else
  6785. PotentialModified := True;
  6786. end;
  6787. else
  6788. { Don't know how to change this, so abort }
  6789. Exit;
  6790. end;
  6791. { Contains highest index (so instruction count - 1) }
  6792. Inc(InstrMax);
  6793. if InstrMax > High(InstrList) then
  6794. SetLength(InstrList, InstrMax + LIST_STEP_SIZE);
  6795. InstrList[InstrMax] := taicpu(next);
  6796. end;
  6797. UpdateUsedRegs(TmpUsedRegs, tai(next.next));
  6798. end;
  6799. if not Assigned(next) or (next <> hp1) then
  6800. { It should be equal to hp1 }
  6801. InternalError(2021051702);
  6802. { Cycle through each instruction and check to see if we can
  6803. change them to versions that don't modify the flags }
  6804. if (InstrMax >= 0) then
  6805. begin
  6806. for Index := 0 to InstrMax do
  6807. case InstrList[Index].opcode of
  6808. A_ADD:
  6809. begin
  6810. DebugMsg(SPeepholeOptimization + 'ADD -> LEA' + SNoFlags, InstrList[Index]);
  6811. InstrList[Index].opcode := A_LEA;
  6812. reference_reset(NewRef, 1, []);
  6813. NewRef.base := InstrList[Index].oper[1]^.reg;
  6814. if InstrList[Index].oper[0]^.typ = top_reg then
  6815. begin
  6816. NewRef.index := InstrList[Index].oper[0]^.reg;
  6817. NewRef.scalefactor := 1;
  6818. end
  6819. else
  6820. NewRef.offset := InstrList[Index].oper[0]^.val;
  6821. InstrList[Index].loadref(0, NewRef);
  6822. end;
  6823. A_SUB:
  6824. begin
  6825. DebugMsg(SPeepholeOptimization + 'SUB -> LEA' + SNoFlags, InstrList[Index]);
  6826. InstrList[Index].opcode := A_LEA;
  6827. reference_reset(NewRef, 1, []);
  6828. NewRef.base := InstrList[Index].oper[1]^.reg;
  6829. NewRef.offset := -InstrList[Index].oper[0]^.val;
  6830. InstrList[Index].loadref(0, NewRef);
  6831. end;
  6832. A_SHL,
  6833. A_SAL:
  6834. begin
  6835. DebugMsg(SPeepholeOptimization + 'SHL -> LEA' + SNoFlags, InstrList[Index]);
  6836. InstrList[Index].opcode := A_LEA;
  6837. reference_reset(NewRef, 1, []);
  6838. NewRef.index := InstrList[Index].oper[1]^.reg;
  6839. NewRef.scalefactor := 1 shl (InstrList[Index].oper[0]^.val);
  6840. InstrList[Index].loadref(0, NewRef);
  6841. end;
  6842. A_IMUL:
  6843. begin
  6844. DebugMsg(SPeepholeOptimization + 'IMUL -> LEA' + SNoFlags, InstrList[Index]);
  6845. InstrList[Index].opcode := A_LEA;
  6846. reference_reset(NewRef, 1, []);
  6847. NewRef.index := InstrList[Index].oper[1]^.reg;
  6848. case InstrList[Index].oper[0]^.val of
  6849. 2, 4, 8:
  6850. NewRef.scalefactor := InstrList[Index].oper[0]^.val;
  6851. else {3, 5 and 9}
  6852. begin
  6853. NewRef.scalefactor := InstrList[Index].oper[0]^.val - 1;
  6854. NewRef.base := InstrList[Index].oper[1]^.reg;
  6855. end;
  6856. end;
  6857. InstrList[Index].loadref(0, NewRef);
  6858. end;
  6859. else
  6860. InternalError(2021051710);
  6861. end;
  6862. end;
  6863. { Mark the FLAGS register as used across this whole block }
  6864. AllocRegBetween(NR_DEFAULTFLAGS, p, hp1, UsedRegs);
  6865. end;
  6866. UpdateUsedRegs(TmpUsedRegs, tai(hp1.next));
  6867. JumpC := taicpu(hp2).condition;
  6868. Unconditional := False;
  6869. if conditions_equal(JumpC, C_E) then
  6870. SetC := inverse_cond(taicpu(p).condition)
  6871. else if conditions_equal(JumpC, C_NE) then
  6872. SetC := taicpu(p).condition
  6873. else
  6874. { We've got something weird here (and inefficent) }
  6875. begin
  6876. DebugMsg('DEBUG: Inefficient jump - check code generation', p);
  6877. SetC := C_NONE;
  6878. { JAE/JNB will always branch (use 'condition_in', since C_AE <> C_NB normally) }
  6879. if condition_in(C_AE, JumpC) then
  6880. Unconditional := True
  6881. else
  6882. { Not sure what to do with this jump - drop out }
  6883. Exit;
  6884. end;
  6885. RemoveInstruction(hp1);
  6886. if Unconditional then
  6887. MakeUnconditional(taicpu(hp2))
  6888. else
  6889. begin
  6890. if SetC = C_NONE then
  6891. InternalError(2018061402);
  6892. taicpu(hp2).SetCondition(SetC);
  6893. end;
  6894. { as hp2 is a jump, we cannot use RegUsedAfterInstruction but we have to check if it is included in
  6895. TmpUsedRegs }
  6896. if not TmpUsedRegs[getregtype(taicpu(p).oper[0]^.reg)].IsUsed(taicpu(p).oper[0]^.reg) then
  6897. begin
  6898. RemoveCurrentp(p, hp2);
  6899. if taicpu(hp2).opcode = A_SETcc then
  6900. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc',p)
  6901. else
  6902. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> Jcc',p);
  6903. end
  6904. else
  6905. if taicpu(hp2).opcode = A_SETcc then
  6906. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/SETcc -> SETcc/SETcc',p)
  6907. else
  6908. DebugMsg(SPeepholeOptimization + 'SETcc/TEST/Jcc -> SETcc/Jcc',p);
  6909. Result := True;
  6910. end
  6911. else if
  6912. { Make sure the instructions are adjacent }
  6913. (
  6914. not (cs_opt_level3 in current_settings.optimizerswitches) or
  6915. GetNextInstruction(p, hp1)
  6916. ) and
  6917. MatchInstruction(hp1, A_MOV, [S_B]) and
  6918. { Writing to memory is allowed }
  6919. MatchOperand(taicpu(p).oper[0]^, taicpu(hp1).oper[0]^.reg) then
  6920. begin
  6921. {
  6922. Watch out for sequences such as:
  6923. set(c)b %regb
  6924. movb %regb,(ref)
  6925. movb $0,1(ref)
  6926. movb $0,2(ref)
  6927. movb $0,3(ref)
  6928. Much more efficient to turn it into:
  6929. movl $0,%regl
  6930. set(c)b %regb
  6931. movl %regl,(ref)
  6932. Or:
  6933. set(c)b %regb
  6934. movzbl %regb,%regl
  6935. movl %regl,(ref)
  6936. }
  6937. if (taicpu(hp1).oper[1]^.typ = top_ref) and
  6938. GetNextInstruction(hp1, hp2) and
  6939. MatchInstruction(hp2, A_MOV, [S_B]) and
  6940. (taicpu(hp2).oper[1]^.typ = top_ref) and
  6941. CheckMemoryWrite(taicpu(hp1), taicpu(hp2)) then
  6942. begin
  6943. { Don't do anything else except set Result to True }
  6944. end
  6945. else
  6946. begin
  6947. if taicpu(p).oper[0]^.typ = top_reg then
  6948. begin
  6949. TransferUsedRegs(TmpUsedRegs);
  6950. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  6951. end;
  6952. { If it's not a register, it's a memory address }
  6953. if (taicpu(p).oper[0]^.typ <> top_reg) or RegUsedAfterInstruction(taicpu(p).oper[0]^.reg, hp1, TmpUsedRegs) then
  6954. begin
  6955. { Even if the register is still in use, we can minimise the
  6956. pipeline stall by changing the MOV into another SETcc. }
  6957. taicpu(hp1).opcode := A_SETcc;
  6958. taicpu(hp1).condition := taicpu(p).condition;
  6959. if taicpu(hp1).oper[1]^.typ = top_ref then
  6960. begin
  6961. { Swapping the operand pointers like this is probably a
  6962. bit naughty, but it is far faster than using loadoper
  6963. to transfer the reference from oper[1] to oper[0] if
  6964. you take into account the extra procedure calls and
  6965. the memory allocation and deallocation required }
  6966. OperPtr := taicpu(hp1).oper[1];
  6967. taicpu(hp1).oper[1] := taicpu(hp1).oper[0];
  6968. taicpu(hp1).oper[0] := OperPtr;
  6969. end
  6970. else
  6971. taicpu(hp1).oper[0]^.reg := taicpu(hp1).oper[1]^.reg;
  6972. taicpu(hp1).clearop(1);
  6973. taicpu(hp1).ops := 1;
  6974. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc/SETcc',p);
  6975. end
  6976. else
  6977. begin
  6978. if taicpu(hp1).oper[1]^.typ = top_reg then
  6979. AllocRegBetween(taicpu(hp1).oper[1]^.reg,p,hp1,UsedRegs);
  6980. taicpu(p).loadoper(0, taicpu(hp1).oper[1]^);
  6981. RemoveInstruction(hp1);
  6982. DebugMsg(SPeepholeOptimization + 'SETcc/Mov -> SETcc',p);
  6983. end
  6984. end;
  6985. Result := True;
  6986. end;
  6987. end;
  6988. end;
  6989. function TX86AsmOptimizer.OptPass2Jmp(var p : tai) : boolean;
  6990. var
  6991. hp1: tai;
  6992. Count: Integer;
  6993. OrigLabel: TAsmLabel;
  6994. begin
  6995. result := False;
  6996. { Sometimes, the optimisations below can permit this }
  6997. RemoveDeadCodeAfterJump(p);
  6998. 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
  6999. (taicpu(p).oper[0]^.ref^.index=NR_NO) and (taicpu(p).oper[0]^.ref^.symbol is tasmlabel) then
  7000. begin
  7001. OrigLabel := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7002. { Also a side-effect of optimisations }
  7003. if CollapseZeroDistJump(p, OrigLabel) then
  7004. begin
  7005. Result := True;
  7006. Exit;
  7007. end;
  7008. hp1 := GetLabelWithSym(OrigLabel);
  7009. if (taicpu(p).condition=C_None) and assigned(hp1) and SkipLabels(hp1,hp1) and (hp1.typ = ait_instruction) then
  7010. begin
  7011. case taicpu(hp1).opcode of
  7012. A_RET:
  7013. {
  7014. change
  7015. jmp .L1
  7016. ...
  7017. .L1:
  7018. ret
  7019. into
  7020. ret
  7021. }
  7022. begin
  7023. ConvertJumpToRET(p, hp1);
  7024. result:=true;
  7025. end;
  7026. { Check any kind of direct assignment instruction }
  7027. A_MOV,
  7028. A_MOVD,
  7029. A_MOVQ,
  7030. A_MOVSX,
  7031. {$ifdef x86_64}
  7032. A_MOVSXD,
  7033. {$endif x86_64}
  7034. A_MOVZX,
  7035. A_MOVAPS,
  7036. A_MOVUPS,
  7037. A_MOVSD,
  7038. A_MOVAPD,
  7039. A_MOVUPD,
  7040. A_MOVDQA,
  7041. A_MOVDQU,
  7042. A_VMOVSS,
  7043. A_VMOVAPS,
  7044. A_VMOVUPS,
  7045. A_VMOVSD,
  7046. A_VMOVAPD,
  7047. A_VMOVUPD,
  7048. A_VMOVDQA,
  7049. A_VMOVDQU:
  7050. if ((current_settings.optimizerswitches * [cs_opt_level3, cs_opt_size]) <> [cs_opt_size]) and
  7051. CheckJumpMovTransferOpt(p, hp1, 0, Count) then
  7052. begin
  7053. Result := True;
  7054. Exit;
  7055. end;
  7056. else
  7057. ;
  7058. end;
  7059. end;
  7060. end;
  7061. end;
  7062. class function TX86AsmOptimizer.CanBeCMOV(p : tai) : boolean;
  7063. begin
  7064. CanBeCMOV:=assigned(p) and
  7065. MatchInstruction(p,A_MOV,[S_W,S_L,S_Q]) and
  7066. { we can't use cmov ref,reg because
  7067. ref could be nil and cmov still throws an exception
  7068. if ref=nil but the mov isn't done (FK)
  7069. or ((taicpu(p).oper[0]^.typ = top_ref) and
  7070. (taicpu(p).oper[0]^.ref^.refaddr = addr_no))
  7071. }
  7072. (taicpu(p).oper[1]^.typ = top_reg) and
  7073. (
  7074. (taicpu(p).oper[0]^.typ = top_reg) or
  7075. { allow references, but only pure symbols or got rel. addressing with RIP as based,
  7076. it is not expected that this can cause a seg. violation }
  7077. (
  7078. (taicpu(p).oper[0]^.typ = top_ref) and
  7079. IsRefSafe(taicpu(p).oper[0]^.ref)
  7080. )
  7081. );
  7082. end;
  7083. function TX86AsmOptimizer.OptPass2Jcc(var p : tai) : boolean;
  7084. var
  7085. hp1,hp2: tai;
  7086. {$ifndef i8086}
  7087. hp3,hp4,hpmov2, hp5: tai;
  7088. l : Longint;
  7089. condition : TAsmCond;
  7090. {$endif i8086}
  7091. carryadd_opcode : TAsmOp;
  7092. symbol: TAsmSymbol;
  7093. reg: tsuperregister;
  7094. increg, tmpreg: TRegister;
  7095. begin
  7096. result:=false;
  7097. if GetNextInstruction(p,hp1) and (hp1.typ=ait_instruction) then
  7098. begin
  7099. symbol := TAsmLabel(taicpu(p).oper[0]^.ref^.symbol);
  7100. if (
  7101. (
  7102. ((Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB)) and
  7103. MatchOptype(Taicpu(hp1),top_const,top_reg) and
  7104. (Taicpu(hp1).oper[0]^.val=1)
  7105. ) or
  7106. ((Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC))
  7107. ) and
  7108. GetNextInstruction(hp1,hp2) and
  7109. SkipAligns(hp2, hp2) and
  7110. (hp2.typ = ait_label) and
  7111. (Tasmlabel(symbol) = Tai_label(hp2).labsym) then
  7112. { jb @@1 cmc
  7113. inc/dec operand --> adc/sbb operand,0
  7114. @@1:
  7115. ... and ...
  7116. jnb @@1
  7117. inc/dec operand --> adc/sbb operand,0
  7118. @@1: }
  7119. begin
  7120. if Taicpu(p).condition in [C_NAE,C_B,C_C] then
  7121. begin
  7122. case taicpu(hp1).opcode of
  7123. A_INC,
  7124. A_ADD:
  7125. carryadd_opcode:=A_ADC;
  7126. A_DEC,
  7127. A_SUB:
  7128. carryadd_opcode:=A_SBB;
  7129. else
  7130. InternalError(2021011001);
  7131. end;
  7132. Taicpu(p).clearop(0);
  7133. Taicpu(p).ops:=0;
  7134. Taicpu(p).is_jmp:=false;
  7135. Taicpu(p).opcode:=A_CMC;
  7136. Taicpu(p).condition:=C_NONE;
  7137. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2CmcAdc/Sbb',p);
  7138. Taicpu(hp1).ops:=2;
  7139. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  7140. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  7141. else
  7142. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  7143. Taicpu(hp1).loadconst(0,0);
  7144. Taicpu(hp1).opcode:=carryadd_opcode;
  7145. result:=true;
  7146. exit;
  7147. end
  7148. else if Taicpu(p).condition in [C_AE,C_NB,C_NC] then
  7149. begin
  7150. case taicpu(hp1).opcode of
  7151. A_INC,
  7152. A_ADD:
  7153. carryadd_opcode:=A_ADC;
  7154. A_DEC,
  7155. A_SUB:
  7156. carryadd_opcode:=A_SBB;
  7157. else
  7158. InternalError(2021011002);
  7159. end;
  7160. Taicpu(hp1).ops:=2;
  7161. DebugMsg(SPeepholeOptimization+'JccAdd/Inc/Dec2Adc/Sbb',p);
  7162. if (Taicpu(hp1).opcode=A_ADD) or (Taicpu(hp1).opcode=A_SUB) then
  7163. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[1]^)
  7164. else
  7165. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^);
  7166. Taicpu(hp1).loadconst(0,0);
  7167. Taicpu(hp1).opcode:=carryadd_opcode;
  7168. RemoveCurrentP(p, hp1);
  7169. result:=true;
  7170. exit;
  7171. end
  7172. {
  7173. jcc @@1 setcc tmpreg
  7174. inc/dec/add/sub operand -> (movzx tmpreg)
  7175. @@1: add/sub tmpreg,operand
  7176. While this increases code size slightly, it makes the code much faster if the
  7177. jump is unpredictable
  7178. }
  7179. else if not(cs_opt_size in current_settings.optimizerswitches) then
  7180. begin
  7181. { search for an available register which is volatile }
  7182. for reg in tcpuregisterset do
  7183. begin
  7184. if
  7185. {$if defined(i386) or defined(i8086)}
  7186. { Only use registers whose lowest 8-bits can Be accessed }
  7187. (reg in [RS_EAX,RS_EBX,RS_ECX,RS_EDX]) and
  7188. {$endif i386 or i8086}
  7189. (reg in paramanager.get_volatile_registers_int(current_procinfo.procdef.proccalloption)) and
  7190. not(reg in UsedRegs[R_INTREGISTER].GetUsedRegs)
  7191. { We don't need to check if tmpreg is in hp1 or not, because
  7192. it will be marked as in use at p (if not, this is
  7193. indictive of a compiler bug). }
  7194. then
  7195. begin
  7196. TAsmLabel(symbol).decrefs;
  7197. increg := newreg(R_INTREGISTER,reg,R_SUBL);
  7198. Taicpu(p).clearop(0);
  7199. Taicpu(p).ops:=1;
  7200. Taicpu(p).is_jmp:=false;
  7201. Taicpu(p).opcode:=A_SETcc;
  7202. DebugMsg(SPeepholeOptimization+'JccAdd2SetccAdd',p);
  7203. Taicpu(p).condition:=inverse_cond(Taicpu(p).condition);
  7204. Taicpu(p).loadreg(0,increg);
  7205. if getsubreg(Taicpu(hp1).oper[1]^.reg)<>R_SUBL then
  7206. begin
  7207. case getsubreg(Taicpu(hp1).oper[1]^.reg) of
  7208. R_SUBW:
  7209. begin
  7210. tmpreg := newreg(R_INTREGISTER,reg,R_SUBW);
  7211. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BW,increg,tmpreg);
  7212. end;
  7213. R_SUBD:
  7214. begin
  7215. tmpreg := newreg(R_INTREGISTER,reg,R_SUBD);
  7216. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,tmpreg);
  7217. end;
  7218. {$ifdef x86_64}
  7219. R_SUBQ:
  7220. begin
  7221. { MOVZX doesn't have a 64-bit variant, because
  7222. the 32-bit version implicitly zeroes the
  7223. upper 32-bits of the destination register }
  7224. hp2:=Taicpu.op_reg_reg(A_MOVZX,S_BL,increg,
  7225. newreg(R_INTREGISTER,reg,R_SUBD));
  7226. tmpreg := newreg(R_INTREGISTER,reg,R_SUBQ);
  7227. end;
  7228. {$endif x86_64}
  7229. else
  7230. Internalerror(2020030601);
  7231. end;
  7232. taicpu(hp2).fileinfo:=taicpu(hp1).fileinfo;
  7233. asml.InsertAfter(hp2,p);
  7234. end
  7235. else
  7236. tmpreg := increg;
  7237. if (Taicpu(hp1).opcode=A_INC) or (Taicpu(hp1).opcode=A_DEC) then
  7238. begin
  7239. Taicpu(hp1).ops:=2;
  7240. Taicpu(hp1).loadoper(1,Taicpu(hp1).oper[0]^)
  7241. end;
  7242. Taicpu(hp1).loadreg(0,tmpreg);
  7243. AllocRegBetween(tmpreg,p,hp1,UsedRegs);
  7244. Result := True;
  7245. { p is no longer a Jcc instruction, so exit }
  7246. Exit;
  7247. end;
  7248. end;
  7249. end;
  7250. end;
  7251. { Detect the following:
  7252. jmp<cond> @Lbl1
  7253. jmp @Lbl2
  7254. ...
  7255. @Lbl1:
  7256. ret
  7257. Change to:
  7258. jmp<inv_cond> @Lbl2
  7259. ret
  7260. }
  7261. if MatchInstruction(hp1,A_JMP,[]) and (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  7262. begin
  7263. hp2:=getlabelwithsym(TAsmLabel(symbol));
  7264. if Assigned(hp2) and SkipLabels(hp2,hp2) and
  7265. MatchInstruction(hp2,A_RET,[S_NO]) then
  7266. begin
  7267. taicpu(p).condition := inverse_cond(taicpu(p).condition);
  7268. { Change label address to that of the unconditional jump }
  7269. taicpu(p).loadoper(0, taicpu(hp1).oper[0]^);
  7270. TAsmLabel(symbol).DecRefs;
  7271. taicpu(hp1).opcode := A_RET;
  7272. taicpu(hp1).is_jmp := false;
  7273. taicpu(hp1).ops := taicpu(hp2).ops;
  7274. DebugMsg(SPeepholeOptimization+'JccJmpRet2J!ccRet',p);
  7275. case taicpu(hp2).ops of
  7276. 0:
  7277. taicpu(hp1).clearop(0);
  7278. 1:
  7279. taicpu(hp1).loadconst(0,taicpu(hp2).oper[0]^.val);
  7280. else
  7281. internalerror(2016041302);
  7282. end;
  7283. end;
  7284. {$ifndef i8086}
  7285. end
  7286. {
  7287. convert
  7288. j<c> .L1
  7289. mov 1,reg
  7290. jmp .L2
  7291. .L1
  7292. mov 0,reg
  7293. .L2
  7294. into
  7295. mov 0,reg
  7296. set<not(c)> reg
  7297. take care of alignment and that the mov 0,reg is not converted into a xor as this
  7298. would destroy the flag contents
  7299. }
  7300. else if MatchInstruction(hp1,A_MOV,[]) and
  7301. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7302. {$ifdef i386}
  7303. (
  7304. { Under i386, ESI, EDI, EBP and ESP
  7305. don't have an 8-bit representation }
  7306. not (getsupreg(taicpu(hp1).oper[1]^.reg) in [RS_ESI, RS_EDI, RS_EBP, RS_ESP])
  7307. ) and
  7308. {$endif i386}
  7309. (taicpu(hp1).oper[0]^.val=1) and
  7310. GetNextInstruction(hp1,hp2) and
  7311. MatchInstruction(hp2,A_JMP,[]) and (taicpu(hp2).oper[0]^.ref^.refaddr=addr_full) and
  7312. GetNextInstruction(hp2,hp3) and
  7313. { skip align }
  7314. ((hp3.typ<>ait_align) or GetNextInstruction(hp3,hp3)) and
  7315. (hp3.typ=ait_label) and
  7316. (tasmlabel(taicpu(p).oper[0]^.ref^.symbol)=tai_label(hp3).labsym) and
  7317. (tai_label(hp3).labsym.getrefs=1) and
  7318. GetNextInstruction(hp3,hp4) and
  7319. MatchInstruction(hp4,A_MOV,[]) and
  7320. MatchOpType(taicpu(hp4),top_const,top_reg) and
  7321. (taicpu(hp4).oper[0]^.val=0) and
  7322. MatchOperand(taicpu(hp1).oper[1]^,taicpu(hp4).oper[1]^) and
  7323. GetNextInstruction(hp4,hp5) and
  7324. (hp5.typ=ait_label) and
  7325. (tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol)=tai_label(hp5).labsym) and
  7326. (tai_label(hp5).labsym.getrefs=1) then
  7327. begin
  7328. AllocRegBetween(NR_FLAGS,p,hp4,UsedRegs);
  7329. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2MovSetcc',p);
  7330. { remove last label }
  7331. RemoveInstruction(hp5);
  7332. { remove second label }
  7333. RemoveInstruction(hp3);
  7334. { if align is present remove it }
  7335. if GetNextInstruction(hp2,hp3) and (hp3.typ=ait_align) then
  7336. RemoveInstruction(hp3);
  7337. { remove jmp }
  7338. RemoveInstruction(hp2);
  7339. if taicpu(hp1).opsize=S_B then
  7340. RemoveInstruction(hp1)
  7341. else
  7342. taicpu(hp1).loadconst(0,0);
  7343. taicpu(hp4).opcode:=A_SETcc;
  7344. taicpu(hp4).opsize:=S_B;
  7345. taicpu(hp4).condition:=inverse_cond(taicpu(p).condition);
  7346. taicpu(hp4).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(hp4).oper[1]^.reg),R_SUBL));
  7347. taicpu(hp4).opercnt:=1;
  7348. taicpu(hp4).ops:=1;
  7349. taicpu(hp4).freeop(1);
  7350. RemoveCurrentP(p);
  7351. Result:=true;
  7352. exit;
  7353. end
  7354. else if CPUX86_HAS_CMOV in cpu_capabilities[current_settings.cputype] then
  7355. begin
  7356. { check for
  7357. jCC xxx
  7358. <several movs>
  7359. xxx:
  7360. }
  7361. l:=0;
  7362. while assigned(hp1) and
  7363. CanBeCMOV(hp1) and
  7364. { stop on labels }
  7365. not(hp1.typ=ait_label) do
  7366. begin
  7367. inc(l);
  7368. GetNextInstruction(hp1,hp1);
  7369. end;
  7370. if assigned(hp1) then
  7371. begin
  7372. if FindLabel(tasmlabel(symbol),hp1) then
  7373. begin
  7374. if (l<=4) and (l>0) then
  7375. begin
  7376. condition:=inverse_cond(taicpu(p).condition);
  7377. GetNextInstruction(p,hp1);
  7378. repeat
  7379. if not Assigned(hp1) then
  7380. InternalError(2018062900);
  7381. taicpu(hp1).opcode:=A_CMOVcc;
  7382. taicpu(hp1).condition:=condition;
  7383. UpdateUsedRegs(hp1);
  7384. GetNextInstruction(hp1,hp1);
  7385. until not(CanBeCMOV(hp1));
  7386. { Remember what hp1 is in case there's multiple aligns to get rid of }
  7387. hp2 := hp1;
  7388. repeat
  7389. if not Assigned(hp2) then
  7390. InternalError(2018062910);
  7391. case hp2.typ of
  7392. ait_label:
  7393. { What we expected - break out of the loop (it won't be a dead label at the top of
  7394. a cluster because that was optimised at an earlier stage) }
  7395. Break;
  7396. ait_align:
  7397. { Go to the next entry until a label is found (may be multiple aligns before it) }
  7398. begin
  7399. hp2 := tai(hp2.Next);
  7400. Continue;
  7401. end;
  7402. else
  7403. begin
  7404. { Might be a comment or temporary allocation entry }
  7405. if not (hp2.typ in SkipInstr) then
  7406. InternalError(2018062911);
  7407. hp2 := tai(hp2.Next);
  7408. Continue;
  7409. end;
  7410. end;
  7411. until False;
  7412. { Now we can safely decrement the reference count }
  7413. tasmlabel(symbol).decrefs;
  7414. DebugMsg(SPeepholeOptimization+'JccMov2CMov',p);
  7415. { Remove the original jump }
  7416. RemoveInstruction(p); { Note, the choice to not use RemoveCurrentp is deliberate }
  7417. GetNextInstruction(hp2, p); { Instruction after the label }
  7418. { Remove the label if this is its final reference }
  7419. if (tasmlabel(symbol).getrefs=0) then
  7420. StripLabelFast(hp1);
  7421. if Assigned(p) then
  7422. begin
  7423. UpdateUsedRegs(p);
  7424. result:=true;
  7425. end;
  7426. exit;
  7427. end;
  7428. end
  7429. else
  7430. begin
  7431. { check further for
  7432. jCC xxx
  7433. <several movs 1>
  7434. jmp yyy
  7435. xxx:
  7436. <several movs 2>
  7437. yyy:
  7438. }
  7439. { hp2 points to jmp yyy }
  7440. hp2:=hp1;
  7441. { skip hp1 to xxx (or an align right before it) }
  7442. GetNextInstruction(hp1, hp1);
  7443. if assigned(hp2) and
  7444. assigned(hp1) and
  7445. (l<=3) and
  7446. (hp2.typ=ait_instruction) and
  7447. (taicpu(hp2).is_jmp) and
  7448. (taicpu(hp2).condition=C_None) and
  7449. { real label and jump, no further references to the
  7450. label are allowed }
  7451. (tasmlabel(symbol).getrefs=1) and
  7452. FindLabel(tasmlabel(symbol),hp1) then
  7453. begin
  7454. l:=0;
  7455. { skip hp1 to <several moves 2> }
  7456. if (hp1.typ = ait_align) then
  7457. GetNextInstruction(hp1, hp1);
  7458. GetNextInstruction(hp1, hpmov2);
  7459. hp1 := hpmov2;
  7460. while assigned(hp1) and
  7461. CanBeCMOV(hp1) do
  7462. begin
  7463. inc(l);
  7464. GetNextInstruction(hp1, hp1);
  7465. end;
  7466. { hp1 points to yyy (or an align right before it) }
  7467. hp3 := hp1;
  7468. if assigned(hp1) and
  7469. FindLabel(tasmlabel(taicpu(hp2).oper[0]^.ref^.symbol),hp1) then
  7470. begin
  7471. condition:=inverse_cond(taicpu(p).condition);
  7472. GetNextInstruction(p,hp1);
  7473. repeat
  7474. taicpu(hp1).opcode:=A_CMOVcc;
  7475. taicpu(hp1).condition:=condition;
  7476. UpdateUsedRegs(hp1);
  7477. GetNextInstruction(hp1,hp1);
  7478. until not(assigned(hp1)) or
  7479. not(CanBeCMOV(hp1));
  7480. condition:=inverse_cond(condition);
  7481. hp1 := hpmov2;
  7482. { hp1 is now at <several movs 2> }
  7483. while Assigned(hp1) and CanBeCMOV(hp1) do
  7484. begin
  7485. taicpu(hp1).opcode:=A_CMOVcc;
  7486. taicpu(hp1).condition:=condition;
  7487. UpdateUsedRegs(hp1);
  7488. GetNextInstruction(hp1,hp1);
  7489. end;
  7490. hp1 := p;
  7491. { Get first instruction after label }
  7492. GetNextInstruction(hp3, p);
  7493. if assigned(p) and (hp3.typ = ait_align) then
  7494. GetNextInstruction(p, p);
  7495. { Don't dereference yet, as doing so will cause
  7496. GetNextInstruction to skip the label and
  7497. optional align marker. [Kit] }
  7498. GetNextInstruction(hp2, hp4);
  7499. DebugMsg(SPeepholeOptimization+'JccMovJmpMov2CMovCMov',hp1);
  7500. { remove jCC }
  7501. RemoveInstruction(hp1);
  7502. { Now we can safely decrement it }
  7503. tasmlabel(symbol).decrefs;
  7504. { Remove label xxx (it will have a ref of zero due to the initial check }
  7505. StripLabelFast(hp4);
  7506. { remove jmp }
  7507. symbol := taicpu(hp2).oper[0]^.ref^.symbol;
  7508. RemoveInstruction(hp2);
  7509. { As before, now we can safely decrement it }
  7510. tasmlabel(symbol).decrefs;
  7511. { Remove label yyy (and the optional alignment) if its reference falls to zero }
  7512. if tasmlabel(symbol).getrefs = 0 then
  7513. StripLabelFast(hp3);
  7514. if Assigned(p) then
  7515. begin
  7516. UpdateUsedRegs(p);
  7517. result:=true;
  7518. end;
  7519. exit;
  7520. end;
  7521. end;
  7522. end;
  7523. end;
  7524. {$endif i8086}
  7525. end;
  7526. end;
  7527. end;
  7528. function TX86AsmOptimizer.OptPass1Movx(var p : tai) : boolean;
  7529. var
  7530. hp1,hp2: tai;
  7531. reg_and_hp1_is_instr: Boolean;
  7532. begin
  7533. result:=false;
  7534. reg_and_hp1_is_instr:=(taicpu(p).oper[1]^.typ = top_reg) and
  7535. GetNextInstruction(p,hp1) and
  7536. (hp1.typ = ait_instruction);
  7537. if reg_and_hp1_is_instr and
  7538. (
  7539. (taicpu(hp1).opcode <> A_LEA) or
  7540. { If the LEA instruction can be converted into an arithmetic instruction,
  7541. it may be possible to then fold it. }
  7542. (
  7543. { If the flags register is in use, don't change the instruction
  7544. to an ADD otherwise this will scramble the flags. [Kit] }
  7545. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  7546. ConvertLEA(taicpu(hp1))
  7547. )
  7548. ) and
  7549. IsFoldableArithOp(taicpu(hp1),taicpu(p).oper[1]^.reg) and
  7550. GetNextInstruction(hp1,hp2) and
  7551. MatchInstruction(hp2,A_MOV,[]) and
  7552. (taicpu(hp2).oper[0]^.typ = top_reg) and
  7553. OpsEqual(taicpu(hp2).oper[1]^,taicpu(p).oper[0]^) and
  7554. ((taicpu(p).opsize in [S_BW,S_BL]) and (taicpu(hp2).opsize=S_B) or
  7555. (taicpu(p).opsize in [S_WL]) and (taicpu(hp2).opsize=S_W)) and
  7556. {$ifdef i386}
  7557. { not all registers have byte size sub registers on i386 }
  7558. ((taicpu(hp2).opsize<>S_B) or (getsupreg(taicpu(hp1).oper[0]^.reg) in [RS_EAX, RS_EBX, RS_ECX, RS_EDX])) and
  7559. {$endif i386}
  7560. (((taicpu(hp1).ops=2) and
  7561. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg))) or
  7562. ((taicpu(hp1).ops=1) and
  7563. (getsupreg(taicpu(hp2).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[0]^.reg)))) and
  7564. not(RegUsedAfterInstruction(taicpu(hp2).oper[0]^.reg,hp2,UsedRegs)) then
  7565. begin
  7566. { change movsX/movzX reg/ref, reg2
  7567. add/sub/or/... reg3/$const, reg2
  7568. mov reg2 reg/ref
  7569. to add/sub/or/... reg3/$const, reg/ref }
  7570. { by example:
  7571. movswl %si,%eax movswl %si,%eax p
  7572. decl %eax addl %edx,%eax hp1
  7573. movw %ax,%si movw %ax,%si hp2
  7574. ->
  7575. movswl %si,%eax movswl %si,%eax p
  7576. decw %eax addw %edx,%eax hp1
  7577. movw %ax,%si movw %ax,%si hp2
  7578. }
  7579. taicpu(hp1).changeopsize(taicpu(hp2).opsize);
  7580. {
  7581. ->
  7582. movswl %si,%eax movswl %si,%eax p
  7583. decw %si addw %dx,%si hp1
  7584. movw %ax,%si movw %ax,%si hp2
  7585. }
  7586. case taicpu(hp1).ops of
  7587. 1:
  7588. taicpu(hp1).loadoper(0,taicpu(hp2).oper[1]^);
  7589. 2:
  7590. begin
  7591. taicpu(hp1).loadoper(1,taicpu(hp2).oper[1]^);
  7592. if (taicpu(hp1).oper[0]^.typ = top_reg) then
  7593. setsubreg(taicpu(hp1).oper[0]^.reg,getsubreg(taicpu(hp2).oper[0]^.reg));
  7594. end;
  7595. else
  7596. internalerror(2008042702);
  7597. end;
  7598. {
  7599. ->
  7600. decw %si addw %dx,%si p
  7601. }
  7602. DebugMsg(SPeepholeOptimization + 'var3',p);
  7603. RemoveCurrentP(p, hp1);
  7604. RemoveInstruction(hp2);
  7605. end
  7606. else if reg_and_hp1_is_instr and
  7607. (taicpu(hp1).opcode = A_MOV) and
  7608. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7609. (MatchOperand(taicpu(p).oper[1]^,taicpu(hp1).oper[0]^)
  7610. {$ifdef x86_64}
  7611. { check for implicit extension to 64 bit }
  7612. or
  7613. ((taicpu(p).opsize in [S_BL,S_WL]) and
  7614. (taicpu(hp1).opsize=S_Q) and
  7615. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg)
  7616. )
  7617. {$endif x86_64}
  7618. )
  7619. then
  7620. begin
  7621. { change
  7622. movx %reg1,%reg2
  7623. mov %reg2,%reg3
  7624. dealloc %reg2
  7625. into
  7626. movx %reg,%reg3
  7627. }
  7628. TransferUsedRegs(TmpUsedRegs);
  7629. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7630. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7631. begin
  7632. DebugMsg(SPeepholeOptimization + 'MovxMov2Movx',p);
  7633. {$ifdef x86_64}
  7634. if (taicpu(p).opsize in [S_BL,S_WL]) and
  7635. (taicpu(hp1).opsize=S_Q) then
  7636. taicpu(p).loadreg(1,newreg(R_INTREGISTER,getsupreg(taicpu(hp1).oper[1]^.reg),R_SUBD))
  7637. else
  7638. {$endif x86_64}
  7639. taicpu(p).loadreg(1,taicpu(hp1).oper[1]^.reg);
  7640. RemoveInstruction(hp1);
  7641. end;
  7642. end
  7643. else if reg_and_hp1_is_instr and
  7644. (taicpu(hp1).opcode = A_MOV) and
  7645. MatchOpType(taicpu(hp1),top_reg,top_reg) and
  7646. (((taicpu(p).opsize in [S_BW,S_BL,S_WL{$ifdef x86_64},S_BQ,S_WQ,S_LQ{$endif x86_64}]) and
  7647. (taicpu(hp1).opsize=S_B)) or
  7648. ((taicpu(p).opsize in [S_WL{$ifdef x86_64},S_WQ,S_LQ{$endif x86_64}]) and
  7649. (taicpu(hp1).opsize=S_W))
  7650. {$ifdef x86_64}
  7651. or ((taicpu(p).opsize=S_LQ) and
  7652. (taicpu(hp1).opsize=S_L))
  7653. {$endif x86_64}
  7654. ) and
  7655. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[0]^.reg) then
  7656. begin
  7657. { change
  7658. movx %reg1,%reg2
  7659. mov %reg2,%reg3
  7660. dealloc %reg2
  7661. into
  7662. mov %reg1,%reg3
  7663. if the second mov accesses only the bits stored in reg1
  7664. }
  7665. TransferUsedRegs(TmpUsedRegs);
  7666. UpdateUsedRegs(TmpUsedRegs, tai(p.next));
  7667. if not(RegUsedAfterInstruction(taicpu(p).oper[1]^.reg,hp1,TmpUsedRegs)) then
  7668. begin
  7669. DebugMsg(SPeepholeOptimization + 'MovxMov2Mov',p);
  7670. if taicpu(p).oper[0]^.typ=top_reg then
  7671. begin
  7672. case taicpu(hp1).opsize of
  7673. S_B:
  7674. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBL));
  7675. S_W:
  7676. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBW));
  7677. S_L:
  7678. taicpu(hp1).loadreg(0,newreg(R_INTREGISTER,getsupreg(taicpu(p).oper[0]^.reg),R_SUBD));
  7679. else
  7680. Internalerror(2020102301);
  7681. end;
  7682. AllocRegBetween(taicpu(hp1).oper[0]^.reg,p,hp1,UsedRegs);
  7683. end
  7684. else
  7685. taicpu(hp1).loadref(0,taicpu(p).oper[0]^.ref^);
  7686. RemoveCurrentP(p);
  7687. result:=true;
  7688. exit;
  7689. end;
  7690. end
  7691. else if reg_and_hp1_is_instr and
  7692. (taicpu(p).oper[0]^.typ = top_reg) and
  7693. (
  7694. (taicpu(hp1).opcode = A_SHL) or (taicpu(hp1).opcode = A_SAL)
  7695. ) and
  7696. (taicpu(hp1).oper[0]^.typ = top_const) and
  7697. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  7698. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  7699. { Minimum shift value allowed is the bit difference between the sizes }
  7700. (taicpu(hp1).oper[0]^.val >=
  7701. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  7702. 8 * (
  7703. tcgsize2size[reg_cgsize(taicpu(p).oper[1]^.reg)] -
  7704. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  7705. )
  7706. ) then
  7707. begin
  7708. { For:
  7709. movsx/movzx %reg1,%reg1 (same register, just different sizes)
  7710. shl/sal ##, %reg1
  7711. Remove the movsx/movzx instruction if the shift overwrites the
  7712. extended bits of the register (e.g. movslq %eax,%rax; shlq $32,%rax
  7713. }
  7714. DebugMsg(SPeepholeOptimization + 'MovxShl2Shl',p);
  7715. RemoveCurrentP(p, hp1);
  7716. Result := True;
  7717. Exit;
  7718. end
  7719. else if reg_and_hp1_is_instr and
  7720. (taicpu(p).oper[0]^.typ = top_reg) and
  7721. (
  7722. ((taicpu(hp1).opcode = A_SHR) and (taicpu(p).opcode = A_MOVZX)) or
  7723. ((taicpu(hp1).opcode = A_SAR) and (taicpu(p).opcode <> A_MOVZX))
  7724. ) and
  7725. (taicpu(hp1).oper[0]^.typ = top_const) and
  7726. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  7727. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  7728. { Minimum shift value allowed is the bit size of the smallest register - 1 }
  7729. (taicpu(hp1).oper[0]^.val <
  7730. { Multiply by 8 because tcgsize2size returns bytes, not bits }
  7731. 8 * (
  7732. tcgsize2size[reg_cgsize(taicpu(p).oper[0]^.reg)]
  7733. )
  7734. ) then
  7735. begin
  7736. { For:
  7737. movsx %reg1,%reg1 movzx %reg1,%reg1 (same register, just different sizes)
  7738. sar ##, %reg1 shr ##, %reg1
  7739. Move the shift to before the movx instruction if the shift value
  7740. is not too large.
  7741. }
  7742. asml.Remove(hp1);
  7743. asml.InsertBefore(hp1, p);
  7744. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  7745. case taicpu(p).opsize of
  7746. s_BW, S_BL{$ifdef x86_64}, S_BQ{$endif}:
  7747. taicpu(hp1).opsize := S_B;
  7748. S_WL{$ifdef x86_64}, S_WQ{$endif}:
  7749. taicpu(hp1).opsize := S_W;
  7750. {$ifdef x86_64}
  7751. S_LQ:
  7752. taicpu(hp1).opsize := S_L;
  7753. {$endif}
  7754. else
  7755. InternalError(2020112401);
  7756. end;
  7757. if (taicpu(hp1).opcode = A_SHR) then
  7758. DebugMsg(SPeepholeOptimization + 'MovzShr2ShrMovz', hp1)
  7759. else
  7760. DebugMsg(SPeepholeOptimization + 'MovsSar2SarMovs', hp1);
  7761. Result := True;
  7762. end
  7763. else if taicpu(p).opcode=A_MOVZX then
  7764. begin
  7765. { removes superfluous And's after movzx's }
  7766. if reg_and_hp1_is_instr and
  7767. (taicpu(hp1).opcode = A_AND) and
  7768. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7769. ((taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg)
  7770. {$ifdef x86_64}
  7771. { check for implicit extension to 64 bit }
  7772. or
  7773. ((taicpu(p).opsize in [S_BL,S_WL]) and
  7774. (taicpu(hp1).opsize=S_Q) and
  7775. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg)
  7776. )
  7777. {$endif x86_64}
  7778. )
  7779. then
  7780. begin
  7781. case taicpu(p).opsize Of
  7782. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7783. if (taicpu(hp1).oper[0]^.val = $ff) then
  7784. begin
  7785. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz1',p);
  7786. RemoveInstruction(hp1);
  7787. Result:=true;
  7788. exit;
  7789. end;
  7790. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7791. if (taicpu(hp1).oper[0]^.val = $ffff) then
  7792. begin
  7793. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz2',p);
  7794. RemoveInstruction(hp1);
  7795. Result:=true;
  7796. exit;
  7797. end;
  7798. {$ifdef x86_64}
  7799. S_LQ:
  7800. if (taicpu(hp1).oper[0]^.val = $ffffffff) then
  7801. begin
  7802. DebugMsg(SPeepholeOptimization + 'MovzAnd2Movz3',p);
  7803. RemoveInstruction(hp1);
  7804. Result:=true;
  7805. exit;
  7806. end;
  7807. {$endif x86_64}
  7808. else
  7809. ;
  7810. end;
  7811. { we cannot get rid of the and, but can we get rid of the movz ?}
  7812. if SuperRegistersEqual(taicpu(p).oper[0]^.reg,taicpu(p).oper[1]^.reg) then
  7813. begin
  7814. case taicpu(p).opsize Of
  7815. S_BL, S_BW{$ifdef x86_64}, S_BQ{$endif x86_64}:
  7816. if (taicpu(hp1).oper[0]^.val and $ff)=taicpu(hp1).oper[0]^.val then
  7817. begin
  7818. DebugMsg(SPeepholeOptimization + 'MovzAnd2And1',p);
  7819. RemoveCurrentP(p,hp1);
  7820. Result:=true;
  7821. exit;
  7822. end;
  7823. S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  7824. if (taicpu(hp1).oper[0]^.val and $ffff)=taicpu(hp1).oper[0]^.val then
  7825. begin
  7826. DebugMsg(SPeepholeOptimization + 'MovzAnd2And2',p);
  7827. RemoveCurrentP(p,hp1);
  7828. Result:=true;
  7829. exit;
  7830. end;
  7831. {$ifdef x86_64}
  7832. S_LQ:
  7833. if (taicpu(hp1).oper[0]^.val and $ffffffff)=taicpu(hp1).oper[0]^.val then
  7834. begin
  7835. DebugMsg(SPeepholeOptimization + 'MovzAnd2And3',p);
  7836. RemoveCurrentP(p,hp1);
  7837. Result:=true;
  7838. exit;
  7839. end;
  7840. {$endif x86_64}
  7841. else
  7842. ;
  7843. end;
  7844. end;
  7845. end;
  7846. { changes some movzx constructs to faster synonyms (all examples
  7847. are given with eax/ax, but are also valid for other registers)}
  7848. if MatchOpType(taicpu(p),top_reg,top_reg) then
  7849. begin
  7850. case taicpu(p).opsize of
  7851. { Technically, movzbw %al,%ax cannot be encoded in 32/64-bit mode
  7852. (the machine code is equivalent to movzbl %al,%eax), but the
  7853. code generator still generates that assembler instruction and
  7854. it is silently converted. This should probably be checked.
  7855. [Kit] }
  7856. S_BW:
  7857. begin
  7858. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7859. (
  7860. not IsMOVZXAcceptable
  7861. { and $0xff,%ax has a smaller encoding but risks a partial write penalty }
  7862. or (
  7863. (cs_opt_size in current_settings.optimizerswitches) and
  7864. (taicpu(p).oper[1]^.reg = NR_AX)
  7865. )
  7866. ) then
  7867. {Change "movzbw %al, %ax" to "andw $0x0ffh, %ax"}
  7868. begin
  7869. DebugMsg(SPeepholeOptimization + 'var7',p);
  7870. taicpu(p).opcode := A_AND;
  7871. taicpu(p).changeopsize(S_W);
  7872. taicpu(p).loadConst(0,$ff);
  7873. Result := True;
  7874. end
  7875. else if not IsMOVZXAcceptable and
  7876. GetNextInstruction(p, hp1) and
  7877. (tai(hp1).typ = ait_instruction) and
  7878. (taicpu(hp1).opcode = A_AND) and
  7879. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7880. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7881. { Change "movzbw %reg1, %reg2; andw $const, %reg2"
  7882. to "movw %reg1, reg2; andw $(const1 and $ff), %reg2"}
  7883. begin
  7884. DebugMsg(SPeepholeOptimization + 'var8',p);
  7885. taicpu(p).opcode := A_MOV;
  7886. taicpu(p).changeopsize(S_W);
  7887. setsubreg(taicpu(p).oper[0]^.reg,R_SUBW);
  7888. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7889. Result := True;
  7890. end;
  7891. end;
  7892. {$ifndef i8086} { movzbl %al,%eax cannot be encoded in 16-bit mode (the machine code is equivalent to movzbw %al,%ax }
  7893. S_BL:
  7894. begin
  7895. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) and
  7896. (
  7897. not IsMOVZXAcceptable
  7898. { and $0xff,%eax has a smaller encoding but risks a partial write penalty }
  7899. or (
  7900. (cs_opt_size in current_settings.optimizerswitches) and
  7901. (taicpu(p).oper[1]^.reg = NR_EAX)
  7902. )
  7903. ) then
  7904. { Change "movzbl %al, %eax" to "andl $0x0ffh, %eax" }
  7905. begin
  7906. DebugMsg(SPeepholeOptimization + 'var9',p);
  7907. taicpu(p).opcode := A_AND;
  7908. taicpu(p).changeopsize(S_L);
  7909. taicpu(p).loadConst(0,$ff);
  7910. Result := True;
  7911. end
  7912. else if not IsMOVZXAcceptable and
  7913. GetNextInstruction(p, hp1) and
  7914. (tai(hp1).typ = ait_instruction) and
  7915. (taicpu(hp1).opcode = A_AND) and
  7916. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7917. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7918. { Change "movzbl %reg1, %reg2; andl $const, %reg2"
  7919. to "movl %reg1, reg2; andl $(const1 and $ff), %reg2"}
  7920. begin
  7921. DebugMsg(SPeepholeOptimization + 'var10',p);
  7922. taicpu(p).opcode := A_MOV;
  7923. taicpu(p).changeopsize(S_L);
  7924. { do not use R_SUBWHOLE
  7925. as movl %rdx,%eax
  7926. is invalid in assembler PM }
  7927. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  7928. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7929. Result := True;
  7930. end;
  7931. end;
  7932. {$endif i8086}
  7933. S_WL:
  7934. if not IsMOVZXAcceptable then
  7935. begin
  7936. if (getsupreg(taicpu(p).oper[0]^.reg)=getsupreg(taicpu(p).oper[1]^.reg)) then
  7937. { Change "movzwl %ax, %eax" to "andl $0x0ffffh, %eax" }
  7938. begin
  7939. DebugMsg(SPeepholeOptimization + 'var11',p);
  7940. taicpu(p).opcode := A_AND;
  7941. taicpu(p).changeopsize(S_L);
  7942. taicpu(p).loadConst(0,$ffff);
  7943. Result := True;
  7944. end
  7945. else if GetNextInstruction(p, hp1) and
  7946. (tai(hp1).typ = ait_instruction) and
  7947. (taicpu(hp1).opcode = A_AND) and
  7948. (taicpu(hp1).oper[0]^.typ = top_const) and
  7949. (taicpu(hp1).oper[1]^.typ = top_reg) and
  7950. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7951. { Change "movzwl %reg1, %reg2; andl $const, %reg2"
  7952. to "movl %reg1, reg2; andl $(const1 and $ffff), %reg2"}
  7953. begin
  7954. DebugMsg(SPeepholeOptimization + 'var12',p);
  7955. taicpu(p).opcode := A_MOV;
  7956. taicpu(p).changeopsize(S_L);
  7957. { do not use R_SUBWHOLE
  7958. as movl %rdx,%eax
  7959. is invalid in assembler PM }
  7960. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  7961. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  7962. Result := True;
  7963. end;
  7964. end;
  7965. else
  7966. InternalError(2017050705);
  7967. end;
  7968. end
  7969. else if not IsMOVZXAcceptable and (taicpu(p).oper[0]^.typ = top_ref) then
  7970. begin
  7971. if GetNextInstruction(p, hp1) and
  7972. (tai(hp1).typ = ait_instruction) and
  7973. (taicpu(hp1).opcode = A_AND) and
  7974. MatchOpType(taicpu(hp1),top_const,top_reg) and
  7975. (taicpu(hp1).oper[1]^.reg = taicpu(p).oper[1]^.reg) then
  7976. begin
  7977. //taicpu(p).opcode := A_MOV;
  7978. case taicpu(p).opsize Of
  7979. S_BL:
  7980. begin
  7981. DebugMsg(SPeepholeOptimization + 'var13',p);
  7982. taicpu(hp1).changeopsize(S_L);
  7983. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7984. end;
  7985. S_WL:
  7986. begin
  7987. DebugMsg(SPeepholeOptimization + 'var14',p);
  7988. taicpu(hp1).changeopsize(S_L);
  7989. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ffff);
  7990. end;
  7991. S_BW:
  7992. begin
  7993. DebugMsg(SPeepholeOptimization + 'var15',p);
  7994. taicpu(hp1).changeopsize(S_W);
  7995. taicpu(hp1).loadConst(0,taicpu(hp1).oper[0]^.val and $ff);
  7996. end;
  7997. else
  7998. Internalerror(2017050704)
  7999. end;
  8000. Result := True;
  8001. end;
  8002. end;
  8003. end;
  8004. end;
  8005. function TX86AsmOptimizer.OptPass1AND(var p : tai) : boolean;
  8006. var
  8007. hp1, hp2 : tai;
  8008. MaskLength : Cardinal;
  8009. MaskedBits : TCgInt;
  8010. begin
  8011. Result:=false;
  8012. { There are no optimisations for reference targets }
  8013. if (taicpu(p).oper[1]^.typ <> top_reg) then
  8014. Exit;
  8015. while GetNextInstruction(p, hp1) and
  8016. (hp1.typ = ait_instruction) do
  8017. begin
  8018. if (taicpu(p).oper[0]^.typ = top_const) then
  8019. begin
  8020. case taicpu(hp1).opcode of
  8021. A_AND:
  8022. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  8023. (getsupreg(taicpu(p).oper[1]^.reg) = getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8024. { the second register must contain the first one, so compare their subreg types }
  8025. (getsubreg(taicpu(p).oper[1]^.reg)<=getsubreg(taicpu(hp1).oper[1]^.reg)) and
  8026. (abs(taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val)<$80000000) then
  8027. { change
  8028. and const1, reg
  8029. and const2, reg
  8030. to
  8031. and (const1 and const2), reg
  8032. }
  8033. begin
  8034. taicpu(hp1).loadConst(0, taicpu(p).oper[0]^.val and taicpu(hp1).oper[0]^.val);
  8035. DebugMsg(SPeepholeOptimization + 'AndAnd2And done',hp1);
  8036. RemoveCurrentP(p, hp1);
  8037. Result:=true;
  8038. exit;
  8039. end;
  8040. A_CMP:
  8041. if (PopCnt(DWord(taicpu(p).oper[0]^.val)) = 1) and { Only 1 bit set }
  8042. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[0]^.val) and
  8043. MatchOperand(taicpu(hp1).oper[1]^, taicpu(p).oper[1]^.reg) and
  8044. { Just check that the condition on the next instruction is compatible }
  8045. GetNextInstruction(hp1, hp2) and
  8046. (hp2.typ = ait_instruction) and
  8047. (taicpu(hp2).condition in [C_Z, C_E, C_NZ, C_NE])
  8048. then
  8049. { change
  8050. and 2^n, reg
  8051. cmp 2^n, reg
  8052. j(c) / set(c) / cmov(c) (c is equal or not equal)
  8053. to
  8054. and 2^n, reg
  8055. test reg, reg
  8056. j(~c) / set(~c) / cmov(~c)
  8057. }
  8058. begin
  8059. { Keep TEST instruction in, rather than remove it, because
  8060. it may trigger other optimisations such as MovAndTest2Test }
  8061. taicpu(hp1).loadreg(0, taicpu(hp1).oper[1]^.reg);
  8062. taicpu(hp1).opcode := A_TEST;
  8063. DebugMsg(SPeepholeOptimization + 'AND/CMP/J(c) -> AND/J(~c) with power of 2 constant', p);
  8064. taicpu(hp2).condition := inverse_cond(taicpu(hp2).condition);
  8065. Result := True;
  8066. Exit;
  8067. end;
  8068. A_MOVZX:
  8069. if MatchOpType(taicpu(hp1),top_reg,top_reg) and
  8070. SuperRegistersEqual(taicpu(p).oper[1]^.reg,taicpu(hp1).oper[1]^.reg) and
  8071. (getsupreg(taicpu(hp1).oper[0]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) and
  8072. (
  8073. (
  8074. (taicpu(p).opsize=S_W) and
  8075. (taicpu(hp1).opsize=S_BW)
  8076. ) or
  8077. (
  8078. (taicpu(p).opsize=S_L) and
  8079. (taicpu(hp1).opsize in [S_WL,S_BL{$ifdef x86_64},S_BQ,S_WQ{$endif x86_64}])
  8080. )
  8081. {$ifdef x86_64}
  8082. or
  8083. (
  8084. (taicpu(p).opsize=S_Q) and
  8085. (taicpu(hp1).opsize in [S_BQ,S_WQ,S_BL,S_WL])
  8086. )
  8087. {$endif x86_64}
  8088. ) then
  8089. begin
  8090. if (((taicpu(hp1).opsize) in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  8091. ((taicpu(p).oper[0]^.val and $ff)=taicpu(p).oper[0]^.val)
  8092. ) or
  8093. (((taicpu(hp1).opsize) in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  8094. ((taicpu(p).oper[0]^.val and $ffff)=taicpu(p).oper[0]^.val))
  8095. then
  8096. begin
  8097. { Unlike MOVSX, MOVZX doesn't actually have a version that zero-extends a
  8098. 32-bit register to a 64-bit register, or even a version called MOVZXD, so
  8099. code that tests for the presence of AND 0xffffffff followed by MOVZX is
  8100. wasted, and is indictive of a compiler bug if it were triggered. [Kit]
  8101. NOTE: To zero-extend from 32 bits to 64 bits, simply use the standard MOV.
  8102. }
  8103. DebugMsg(SPeepholeOptimization + 'AndMovzToAnd done',p);
  8104. RemoveInstruction(hp1);
  8105. { See if there are other optimisations possible }
  8106. Continue;
  8107. end;
  8108. end;
  8109. A_SHL:
  8110. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  8111. (getsupreg(taicpu(p).oper[1]^.reg)=getsupreg(taicpu(hp1).oper[1]^.reg)) then
  8112. begin
  8113. {$ifopt R+}
  8114. {$define RANGE_WAS_ON}
  8115. {$R-}
  8116. {$endif}
  8117. { get length of potential and mask }
  8118. MaskLength:=SizeOf(taicpu(p).oper[0]^.val)*8-BsrQWord(taicpu(p).oper[0]^.val)-1;
  8119. { really a mask? }
  8120. {$ifdef RANGE_WAS_ON}
  8121. {$R+}
  8122. {$endif}
  8123. if (((QWord(1) shl MaskLength)-1)=taicpu(p).oper[0]^.val) and
  8124. { unmasked part shifted out? }
  8125. ((MaskLength+taicpu(hp1).oper[0]^.val)>=topsize2memsize[taicpu(hp1).opsize]) then
  8126. begin
  8127. DebugMsg(SPeepholeOptimization + 'AndShlToShl done',p);
  8128. RemoveCurrentP(p, hp1);
  8129. Result:=true;
  8130. exit;
  8131. end;
  8132. end;
  8133. A_SHR:
  8134. if MatchOpType(taicpu(hp1),top_const,top_reg) and
  8135. (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg) and
  8136. (taicpu(hp1).oper[0]^.val <= 63) then
  8137. begin
  8138. { Does SHR combined with the AND cover all the bits?
  8139. e.g. for "andb $252,%reg; shrb $2,%reg" - the "and" can be removed }
  8140. MaskedBits := taicpu(p).oper[0]^.val or ((TCgInt(1) shl taicpu(hp1).oper[0]^.val) - 1);
  8141. if ((taicpu(p).opsize = S_B) and ((MaskedBits and $FF) = $FF)) or
  8142. ((taicpu(p).opsize = S_W) and ((MaskedBits and $FFFF) = $FFFF)) or
  8143. ((taicpu(p).opsize = S_L) and ((MaskedBits and $FFFFFFFF) = $FFFFFFFF)) then
  8144. begin
  8145. DebugMsg(SPeepholeOptimization + 'AndShrToShr done', p);
  8146. RemoveCurrentP(p, hp1);
  8147. Result := True;
  8148. Exit;
  8149. end;
  8150. end;
  8151. A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif x86_64}:
  8152. if (taicpu(hp1).oper[0]^.typ = top_reg) and
  8153. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^.reg) then
  8154. begin
  8155. if SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  8156. (
  8157. (
  8158. (taicpu(hp1).opsize in [S_BW,S_BL{$ifdef x86_64},S_BQ{$endif x86_64}]) and
  8159. ((taicpu(p).oper[0]^.val and $7F) = taicpu(p).oper[0]^.val)
  8160. ) or (
  8161. (taicpu(hp1).opsize in [S_WL{$ifdef x86_64},S_WQ{$endif x86_64}]) and
  8162. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val)
  8163. {$ifdef x86_64}
  8164. ) or (
  8165. (taicpu(hp1).opsize = S_LQ) and
  8166. ((taicpu(p).oper[0]^.val and $7fffffff) = taicpu(p).oper[0]^.val)
  8167. {$endif x86_64}
  8168. )
  8169. ) then
  8170. begin
  8171. if (taicpu(p).oper[1]^.reg = taicpu(hp1).oper[1]^.reg){$ifdef x86_64} or (taicpu(hp1).opsize = S_LQ){$endif x86_64} then
  8172. begin
  8173. DebugMsg(SPeepholeOptimization + 'AndMovsxToAnd',p);
  8174. RemoveInstruction(hp1);
  8175. { See if there are other optimisations possible }
  8176. Continue;
  8177. end;
  8178. { The super-registers are the same though.
  8179. Note that this change by itself doesn't improve
  8180. code speed, but it opens up other optimisations. }
  8181. {$ifdef x86_64}
  8182. { Convert 64-bit register to 32-bit }
  8183. case taicpu(hp1).opsize of
  8184. S_BQ:
  8185. begin
  8186. taicpu(hp1).opsize := S_BL;
  8187. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  8188. end;
  8189. S_WQ:
  8190. begin
  8191. taicpu(hp1).opsize := S_WL;
  8192. taicpu(hp1).oper[1]^.reg := newreg(R_INTREGISTER, getsupreg(taicpu(hp1).oper[1]^.reg), R_SUBD);
  8193. end
  8194. else
  8195. ;
  8196. end;
  8197. {$endif x86_64}
  8198. DebugMsg(SPeepholeOptimization + 'AndMovsxToAndMovzx', hp1);
  8199. taicpu(hp1).opcode := A_MOVZX;
  8200. { See if there are other optimisations possible }
  8201. Continue;
  8202. end;
  8203. end;
  8204. else
  8205. ;
  8206. end;
  8207. end;
  8208. if (taicpu(hp1).is_jmp) and
  8209. (taicpu(hp1).opcode<>A_JMP) and
  8210. not(RegInUsedRegs(taicpu(p).oper[1]^.reg,UsedRegs)) then
  8211. begin
  8212. { change
  8213. and x, reg
  8214. jxx
  8215. to
  8216. test x, reg
  8217. jxx
  8218. if reg is deallocated before the
  8219. jump, but only if it's a conditional jump (PFV)
  8220. }
  8221. taicpu(p).opcode := A_TEST;
  8222. Exit;
  8223. end;
  8224. Break;
  8225. end;
  8226. { Lone AND tests }
  8227. if (taicpu(p).oper[0]^.typ = top_const) then
  8228. begin
  8229. {
  8230. - Convert and $0xFF,reg to and reg,reg if reg is 8-bit
  8231. - Convert and $0xFFFF,reg to and reg,reg if reg is 16-bit
  8232. - Convert and $0xFFFFFFFF,reg to and reg,reg if reg is 32-bit
  8233. }
  8234. if ((taicpu(p).oper[0]^.val = $FF) and (taicpu(p).opsize = S_B)) or
  8235. ((taicpu(p).oper[0]^.val = $FFFF) and (taicpu(p).opsize = S_W)) or
  8236. ((taicpu(p).oper[0]^.val = $FFFFFFFF) and (taicpu(p).opsize = S_L)) then
  8237. begin
  8238. taicpu(p).loadreg(0, taicpu(p).oper[1]^.reg);
  8239. if taicpu(p).opsize = S_L then
  8240. begin
  8241. Include(OptsToCheck,aoc_MovAnd2Mov_3);
  8242. Result := True;
  8243. end;
  8244. end;
  8245. end;
  8246. { Backward check to determine necessity of and %reg,%reg }
  8247. if (taicpu(p).oper[0]^.typ = top_reg) and
  8248. (taicpu(p).oper[0]^.reg = taicpu(p).oper[1]^.reg) and
  8249. not RegInUsedRegs(NR_DEFAULTFLAGS, UsedRegs) and
  8250. GetLastInstruction(p, hp2) and
  8251. RegModifiedByInstruction(taicpu(p).oper[1]^.reg, hp2) and
  8252. { Check size of adjacent instruction to determine if the AND is
  8253. effectively a null operation }
  8254. (
  8255. (taicpu(p).opsize = taicpu(hp2).opsize) or
  8256. { Note: Don't include S_Q }
  8257. ((taicpu(p).opsize = S_L) and (taicpu(hp2).opsize in [S_BL, S_WL])) or
  8258. ((taicpu(p).opsize = S_W) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_L])) or
  8259. ((taicpu(p).opsize = S_B) and (taicpu(hp2).opsize in [S_BW, S_BL, S_WL, S_W, S_L]))
  8260. ) then
  8261. begin
  8262. DebugMsg(SPeepholeOptimization + 'And2Nop', p);
  8263. { If GetNextInstruction returned False, hp1 will be nil }
  8264. RemoveCurrentP(p, hp1);
  8265. Result := True;
  8266. Exit;
  8267. end;
  8268. end;
  8269. function TX86AsmOptimizer.OptPass2ADD(var p : tai) : boolean;
  8270. var
  8271. hp1: tai; NewRef: TReference;
  8272. { This entire nested function is used in an if-statement below, but we
  8273. want to avoid all the used reg transfers and GetNextInstruction calls
  8274. until we really have to check }
  8275. function MemRegisterNotUsedLater: Boolean; inline;
  8276. var
  8277. hp2: tai;
  8278. begin
  8279. TransferUsedRegs(TmpUsedRegs);
  8280. hp2 := p;
  8281. repeat
  8282. UpdateUsedRegs(TmpUsedRegs, tai(hp2.Next));
  8283. until not GetNextInstruction(hp2, hp2) or (hp2 = hp1);
  8284. Result := not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs);
  8285. end;
  8286. begin
  8287. Result := False;
  8288. if not GetNextInstruction(p, hp1) or (hp1.typ <> ait_instruction) then
  8289. Exit;
  8290. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif}]) then
  8291. begin
  8292. { Change:
  8293. add %reg2,%reg1
  8294. mov/s/z #(%reg1),%reg1 (%reg1 superregisters must be the same)
  8295. To:
  8296. mov/s/z #(%reg1,%reg2),%reg1
  8297. }
  8298. if MatchOpType(taicpu(p), top_reg, top_reg) and
  8299. MatchInstruction(hp1, [A_MOV, A_MOVZX, A_MOVSX{$ifdef x86_64}, A_MOVSXD{$endif}], []) and
  8300. MatchOpType(taicpu(hp1), top_ref, top_reg) and
  8301. (taicpu(hp1).oper[0]^.ref^.scalefactor <= 1) and
  8302. (
  8303. (
  8304. (taicpu(hp1).oper[0]^.ref^.base = taicpu(p).oper[1]^.reg) and
  8305. (taicpu(hp1).oper[0]^.ref^.index = NR_NO) and
  8306. { r/esp cannot be an index }
  8307. (taicpu(p).oper[0]^.reg<>NR_STACK_POINTER_REG)
  8308. ) or (
  8309. (taicpu(hp1).oper[0]^.ref^.index = taicpu(p).oper[1]^.reg) and
  8310. (taicpu(hp1).oper[0]^.ref^.base = NR_NO)
  8311. )
  8312. ) and (
  8313. Reg1WriteOverwritesReg2Entirely(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) or
  8314. (
  8315. { If the super registers ARE equal, then this MOV/S/Z does a partial write }
  8316. not SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) and
  8317. MemRegisterNotUsedLater
  8318. )
  8319. ) then
  8320. begin
  8321. taicpu(hp1).oper[0]^.ref^.base := taicpu(p).oper[1]^.reg;
  8322. taicpu(hp1).oper[0]^.ref^.index := taicpu(p).oper[0]^.reg;
  8323. DebugMsg(SPeepholeOptimization + 'AddMov2Mov done', p);
  8324. RemoveCurrentp(p, hp1);
  8325. Result := True;
  8326. Exit;
  8327. end;
  8328. { Change:
  8329. addl/q $x,%reg1
  8330. movl/q %reg1,%reg2
  8331. To:
  8332. leal/q $x(%reg1),%reg2
  8333. addl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  8334. Breaks the dependency chain.
  8335. }
  8336. if MatchOpType(taicpu(p),top_const,top_reg) and
  8337. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  8338. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8339. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  8340. (
  8341. { Don't do AddMov2LeaAdd under -Os, but do allow AddMov2Lea }
  8342. not (cs_opt_size in current_settings.optimizerswitches) or
  8343. (
  8344. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  8345. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  8346. )
  8347. ) then
  8348. begin
  8349. { Change the MOV instruction to a LEA instruction, and update the
  8350. first operand }
  8351. reference_reset(NewRef, 1, []);
  8352. NewRef.base := taicpu(p).oper[1]^.reg;
  8353. NewRef.scalefactor := 1;
  8354. NewRef.offset := taicpu(p).oper[0]^.val;
  8355. taicpu(hp1).opcode := A_LEA;
  8356. taicpu(hp1).loadref(0, NewRef);
  8357. TransferUsedRegs(TmpUsedRegs);
  8358. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8359. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  8360. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8361. begin
  8362. { Move what is now the LEA instruction to before the SUB instruction }
  8363. Asml.Remove(hp1);
  8364. Asml.InsertBefore(hp1, p);
  8365. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  8366. DebugMsg(SPeepholeOptimization + 'AddMov2LeaAdd', p);
  8367. p := hp1;
  8368. end
  8369. else
  8370. begin
  8371. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  8372. RemoveCurrentP(p, hp1);
  8373. DebugMsg(SPeepholeOptimization + 'AddMov2Lea', p);
  8374. end;
  8375. Result := True;
  8376. end;
  8377. end;
  8378. end;
  8379. function TX86AsmOptimizer.OptPass2Lea(var p : tai) : Boolean;
  8380. begin
  8381. Result:=false;
  8382. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8383. begin
  8384. if MatchReference(taicpu(p).oper[0]^.ref^,taicpu(p).oper[1]^.reg,NR_INVALID) and
  8385. (taicpu(p).oper[0]^.ref^.index<>NR_NO) then
  8386. begin
  8387. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.base);
  8388. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.index);
  8389. taicpu(p).opcode:=A_ADD;
  8390. DebugMsg(SPeepholeOptimization + 'Lea2AddBase done',p);
  8391. result:=true;
  8392. end
  8393. else if MatchReference(taicpu(p).oper[0]^.ref^,NR_INVALID,taicpu(p).oper[1]^.reg) and
  8394. (taicpu(p).oper[0]^.ref^.base<>NR_NO) then
  8395. begin
  8396. taicpu(p).loadreg(1,taicpu(p).oper[0]^.ref^.index);
  8397. taicpu(p).loadreg(0,taicpu(p).oper[0]^.ref^.base);
  8398. taicpu(p).opcode:=A_ADD;
  8399. DebugMsg(SPeepholeOptimization + 'Lea2AddIndex done',p);
  8400. result:=true;
  8401. end;
  8402. end;
  8403. end;
  8404. function TX86AsmOptimizer.OptPass2SUB(var p: tai): Boolean;
  8405. var
  8406. hp1: tai; NewRef: TReference;
  8407. begin
  8408. { Change:
  8409. subl/q $x,%reg1
  8410. movl/q %reg1,%reg2
  8411. To:
  8412. leal/q $-x(%reg1),%reg2
  8413. subl/q $x,%reg1 (can be removed if %reg1 or the flags are not used afterwards)
  8414. Breaks the dependency chain and potentially permits the removal of
  8415. a CMP instruction if one follows.
  8416. }
  8417. Result := False;
  8418. if (taicpu(p).opsize in [S_L{$ifdef x86_64}, S_Q{$endif x86_64}]) and
  8419. MatchOpType(taicpu(p),top_const,top_reg) and
  8420. GetNextInstruction(p, hp1) and
  8421. MatchInstruction(hp1, A_MOV, [taicpu(p).opsize]) and
  8422. (taicpu(hp1).oper[1]^.typ = top_reg) and
  8423. MatchOperand(taicpu(hp1).oper[0]^, taicpu(p).oper[1]^.reg) and
  8424. (
  8425. { Don't do SubMov2LeaSub under -Os, but do allow SubMov2Lea }
  8426. not (cs_opt_size in current_settings.optimizerswitches) or
  8427. (
  8428. not RegUsedAfterInstruction(taicpu(p).oper[1]^.reg, hp1, TmpUsedRegs) and
  8429. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs)
  8430. )
  8431. ) then
  8432. begin
  8433. { Change the MOV instruction to a LEA instruction, and update the
  8434. first operand }
  8435. reference_reset(NewRef, 1, []);
  8436. NewRef.base := taicpu(p).oper[1]^.reg;
  8437. NewRef.scalefactor := 1;
  8438. NewRef.offset := -taicpu(p).oper[0]^.val;
  8439. taicpu(hp1).opcode := A_LEA;
  8440. taicpu(hp1).loadref(0, NewRef);
  8441. TransferUsedRegs(TmpUsedRegs);
  8442. UpdateUsedRegs(TmpUsedRegs, tai(p.Next));
  8443. if RegUsedAfterInstruction(NewRef.base, hp1, TmpUsedRegs) or
  8444. RegUsedAfterInstruction(NR_DEFAULTFLAGS, hp1, TmpUsedRegs) then
  8445. begin
  8446. { Move what is now the LEA instruction to before the SUB instruction }
  8447. Asml.Remove(hp1);
  8448. Asml.InsertBefore(hp1, p);
  8449. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, p, UsedRegs);
  8450. DebugMsg(SPeepholeOptimization + 'SubMov2LeaSub', p);
  8451. p := hp1;
  8452. end
  8453. else
  8454. begin
  8455. { Since %reg1 or the flags aren't used afterwards, we can delete p completely }
  8456. RemoveCurrentP(p, hp1);
  8457. DebugMsg(SPeepholeOptimization + 'SubMov2Lea', p);
  8458. end;
  8459. Result := True;
  8460. end;
  8461. end;
  8462. function TX86AsmOptimizer.SkipSimpleInstructions(var hp1 : tai) : Boolean;
  8463. begin
  8464. { we can skip all instructions not messing with the stack pointer }
  8465. while assigned(hp1) and {MatchInstruction(hp1,[A_LEA,A_MOV,A_MOVQ,A_MOVSQ,A_MOVSX,A_MOVSXD,A_MOVZX,
  8466. A_AND,A_OR,A_XOR,A_ADD,A_SHR,A_SHL,A_IMUL,A_SETcc,A_SAR,A_SUB,A_TEST,A_CMOVcc,
  8467. A_MOVSS,A_MOVSD,A_MOVAPS,A_MOVUPD,A_MOVAPD,A_MOVUPS,
  8468. A_VMOVSS,A_VMOVSD,A_VMOVAPS,A_VMOVUPD,A_VMOVAPD,A_VMOVUPS],[]) and}
  8469. ({(taicpu(hp1).ops=0) or }
  8470. ({(MatchOpType(taicpu(hp1),top_reg,top_reg) or MatchOpType(taicpu(hp1),top_const,top_reg) or
  8471. (MatchOpType(taicpu(hp1),top_ref,top_reg))
  8472. ) and }
  8473. not(RegInInstruction(NR_STACK_POINTER_REG,hp1)) { and not(RegInInstruction(NR_FRAME_POINTER_REG,hp1))}
  8474. )
  8475. ) do
  8476. GetNextInstruction(hp1,hp1);
  8477. Result:=assigned(hp1);
  8478. end;
  8479. function TX86AsmOptimizer.PostPeepholeOptLea(var p : tai) : Boolean;
  8480. var
  8481. hp1, hp2, hp3, hp4, hp5: tai;
  8482. begin
  8483. Result:=false;
  8484. hp5:=nil;
  8485. { replace
  8486. leal(q) x(<stackpointer>),<stackpointer>
  8487. call procname
  8488. leal(q) -x(<stackpointer>),<stackpointer>
  8489. ret
  8490. by
  8491. jmp procname
  8492. but do it only on level 4 because it destroys stack back traces
  8493. }
  8494. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8495. MatchOpType(taicpu(p),top_ref,top_reg) and
  8496. (taicpu(p).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  8497. (taicpu(p).oper[0]^.ref^.index=NR_NO) and
  8498. { the -8 or -24 are not required, but bail out early if possible,
  8499. higher values are unlikely }
  8500. ((taicpu(p).oper[0]^.ref^.offset=-8) or
  8501. (taicpu(p).oper[0]^.ref^.offset=-24)) and
  8502. (taicpu(p).oper[0]^.ref^.symbol=nil) and
  8503. (taicpu(p).oper[0]^.ref^.relsymbol=nil) and
  8504. (taicpu(p).oper[0]^.ref^.segment=NR_NO) and
  8505. (taicpu(p).oper[1]^.reg=NR_STACK_POINTER_REG) and
  8506. GetNextInstruction(p, hp1) and
  8507. { Take a copy of hp1 }
  8508. SetAndTest(hp1, hp4) and
  8509. { trick to skip label }
  8510. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  8511. SkipSimpleInstructions(hp1) and
  8512. MatchInstruction(hp1,A_CALL,[S_NO]) and
  8513. GetNextInstruction(hp1, hp2) and
  8514. MatchInstruction(hp2,A_LEA,[taicpu(p).opsize]) and
  8515. MatchOpType(taicpu(hp2),top_ref,top_reg) and
  8516. (taicpu(hp2).oper[0]^.ref^.offset=-taicpu(p).oper[0]^.ref^.offset) and
  8517. (taicpu(hp2).oper[0]^.ref^.base=NR_STACK_POINTER_REG) and
  8518. (taicpu(hp2).oper[0]^.ref^.index=NR_NO) and
  8519. (taicpu(hp2).oper[0]^.ref^.symbol=nil) and
  8520. (taicpu(hp2).oper[0]^.ref^.relsymbol=nil) and
  8521. (taicpu(hp2).oper[0]^.ref^.segment=NR_NO) and
  8522. (taicpu(hp2).oper[1]^.reg=NR_STACK_POINTER_REG) and
  8523. GetNextInstruction(hp2, hp3) and
  8524. { trick to skip label }
  8525. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  8526. (MatchInstruction(hp3,A_RET,[S_NO]) or
  8527. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  8528. SetAndTest(hp3,hp5) and
  8529. GetNextInstruction(hp3,hp3) and
  8530. MatchInstruction(hp3,A_RET,[S_NO])
  8531. )
  8532. ) and
  8533. (taicpu(hp3).ops=0) then
  8534. begin
  8535. taicpu(hp1).opcode := A_JMP;
  8536. taicpu(hp1).is_jmp := true;
  8537. DebugMsg(SPeepholeOptimization + 'LeaCallLeaRet2Jmp done',p);
  8538. RemoveCurrentP(p, hp4);
  8539. RemoveInstruction(hp2);
  8540. RemoveInstruction(hp3);
  8541. if Assigned(hp5) then
  8542. begin
  8543. AsmL.Remove(hp5);
  8544. ASmL.InsertBefore(hp5,hp1)
  8545. end;
  8546. Result:=true;
  8547. end;
  8548. end;
  8549. function TX86AsmOptimizer.PostPeepholeOptPush(var p : tai) : Boolean;
  8550. {$ifdef x86_64}
  8551. var
  8552. hp1, hp2, hp3, hp4, hp5: tai;
  8553. {$endif x86_64}
  8554. begin
  8555. Result:=false;
  8556. {$ifdef x86_64}
  8557. hp5:=nil;
  8558. { replace
  8559. push %rax
  8560. call procname
  8561. pop %rcx
  8562. ret
  8563. by
  8564. jmp procname
  8565. but do it only on level 4 because it destroys stack back traces
  8566. It depends on the fact, that the sequence push rax/pop rcx is used for stack alignment as rcx is volatile
  8567. for all supported calling conventions
  8568. }
  8569. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8570. MatchOpType(taicpu(p),top_reg) and
  8571. (taicpu(p).oper[0]^.reg=NR_RAX) and
  8572. GetNextInstruction(p, hp1) and
  8573. { Take a copy of hp1 }
  8574. SetAndTest(hp1, hp4) and
  8575. { trick to skip label }
  8576. ((hp1.typ=ait_instruction) or GetNextInstruction(hp1, hp1)) and
  8577. SkipSimpleInstructions(hp1) and
  8578. MatchInstruction(hp1,A_CALL,[S_NO]) and
  8579. GetNextInstruction(hp1, hp2) and
  8580. MatchInstruction(hp2,A_POP,[taicpu(p).opsize]) and
  8581. MatchOpType(taicpu(hp2),top_reg) and
  8582. (taicpu(hp2).oper[0]^.reg=NR_RCX) and
  8583. GetNextInstruction(hp2, hp3) and
  8584. { trick to skip label }
  8585. ((hp3.typ=ait_instruction) or GetNextInstruction(hp3, hp3)) and
  8586. (MatchInstruction(hp3,A_RET,[S_NO]) or
  8587. (MatchInstruction(hp3,A_VZEROUPPER,[S_NO]) and
  8588. SetAndTest(hp3,hp5) and
  8589. GetNextInstruction(hp3,hp3) and
  8590. MatchInstruction(hp3,A_RET,[S_NO])
  8591. )
  8592. ) and
  8593. (taicpu(hp3).ops=0) then
  8594. begin
  8595. taicpu(hp1).opcode := A_JMP;
  8596. taicpu(hp1).is_jmp := true;
  8597. DebugMsg(SPeepholeOptimization + 'PushCallPushRet2Jmp done',p);
  8598. RemoveCurrentP(p, hp4);
  8599. RemoveInstruction(hp2);
  8600. RemoveInstruction(hp3);
  8601. if Assigned(hp5) then
  8602. begin
  8603. AsmL.Remove(hp5);
  8604. ASmL.InsertBefore(hp5,hp1)
  8605. end;
  8606. Result:=true;
  8607. end;
  8608. {$endif x86_64}
  8609. end;
  8610. function TX86AsmOptimizer.PostPeepholeOptMov(var p : tai) : Boolean;
  8611. var
  8612. Value, RegName: string;
  8613. begin
  8614. Result:=false;
  8615. if (taicpu(p).oper[1]^.typ = top_reg) and (taicpu(p).oper[0]^.typ = top_const) then
  8616. begin
  8617. case taicpu(p).oper[0]^.val of
  8618. 0:
  8619. { Don't make this optimisation if the CPU flags are required, since XOR scrambles them }
  8620. if not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8621. begin
  8622. { change "mov $0,%reg" into "xor %reg,%reg" }
  8623. taicpu(p).opcode := A_XOR;
  8624. taicpu(p).loadReg(0,taicpu(p).oper[1]^.reg);
  8625. Result := True;
  8626. end;
  8627. $1..$FFFFFFFF:
  8628. begin
  8629. { Code size reduction by J. Gareth "Kit" Moreton }
  8630. { change 64-bit register to 32-bit register to reduce code size (upper 32 bits will be set to zero) }
  8631. case taicpu(p).opsize of
  8632. S_Q:
  8633. begin
  8634. RegName := debug_regname(taicpu(p).oper[1]^.reg); { 64-bit register name }
  8635. Value := debug_tostr(taicpu(p).oper[0]^.val);
  8636. { The actual optimization }
  8637. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  8638. taicpu(p).changeopsize(S_L);
  8639. DebugMsg(SPeepholeOptimization + 'movq $' + Value + ',' + RegName + ' -> movl $' + Value + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (immediate can be represented with just 32 bits)', p);
  8640. Result := True;
  8641. end;
  8642. else
  8643. { Do nothing };
  8644. end;
  8645. end;
  8646. -1:
  8647. { Don't make this optimisation if the CPU flags are required, since OR scrambles them }
  8648. if (cs_opt_size in current_settings.optimizerswitches) and
  8649. (taicpu(p).opsize <> S_B) and
  8650. not (RegInUsedRegs(NR_DEFAULTFLAGS,UsedRegs)) then
  8651. begin
  8652. { change "mov $-1,%reg" into "or $-1,%reg" }
  8653. { NOTES:
  8654. - No size saving is made when changing a Word-sized assignment unless the register is AX (smaller encoding)
  8655. - This operation creates a false dependency on the register, so only do it when optimising for size
  8656. - 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
  8657. }
  8658. taicpu(p).opcode := A_OR;
  8659. Result := True;
  8660. end;
  8661. end;
  8662. end;
  8663. end;
  8664. function TX86AsmOptimizer.PostPeepholeOptAnd(var p : tai) : boolean;
  8665. var
  8666. hp1: tai;
  8667. begin
  8668. { Detect:
  8669. andw x, %ax (0 <= x < $8000)
  8670. ...
  8671. movzwl %ax,%eax
  8672. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  8673. }
  8674. Result := False; if MatchOpType(taicpu(p), top_const, top_reg) and
  8675. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  8676. ((taicpu(p).oper[0]^.val and $7FFF) = taicpu(p).oper[0]^.val) and
  8677. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  8678. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  8679. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  8680. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  8681. begin
  8682. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via AndMovz2AndCwtl)', hp1);
  8683. taicpu(hp1).opcode := A_CWDE;
  8684. taicpu(hp1).clearop(0);
  8685. taicpu(hp1).clearop(1);
  8686. taicpu(hp1).ops := 0;
  8687. { A change was made, but not with p, so move forward 1 }
  8688. p := tai(p.Next);
  8689. Result := True;
  8690. end;
  8691. end;
  8692. function TX86AsmOptimizer.PostPeepholeOptMOVSX(var p : tai) : boolean;
  8693. begin
  8694. Result := False;
  8695. if not MatchOpType(taicpu(p), top_reg, top_reg) then
  8696. Exit;
  8697. { Convert:
  8698. movswl %ax,%eax -> cwtl
  8699. movslq %eax,%rax -> cdqe
  8700. NOTE: Don't convert movswl %al,%ax to cbw, because cbw and cwde
  8701. refer to the same opcode and depends only on the assembler's
  8702. current operand-size attribute. [Kit]
  8703. }
  8704. with taicpu(p) do
  8705. case opsize of
  8706. S_WL:
  8707. if (oper[0]^.reg = NR_AX) and (oper[1]^.reg = NR_EAX) then
  8708. begin
  8709. DebugMsg(SPeepholeOptimization + 'Converted movswl %ax,%eax to cwtl', p);
  8710. opcode := A_CWDE;
  8711. clearop(0);
  8712. clearop(1);
  8713. ops := 0;
  8714. Result := True;
  8715. end;
  8716. {$ifdef x86_64}
  8717. S_LQ:
  8718. if (oper[0]^.reg = NR_EAX) and (oper[1]^.reg = NR_RAX) then
  8719. begin
  8720. DebugMsg(SPeepholeOptimization + 'Converted movslq %eax,%rax to cltq', p);
  8721. opcode := A_CDQE;
  8722. clearop(0);
  8723. clearop(1);
  8724. ops := 0;
  8725. Result := True;
  8726. end;
  8727. {$endif x86_64}
  8728. else
  8729. ;
  8730. end;
  8731. end;
  8732. function TX86AsmOptimizer.PostPeepholeOptShr(var p : tai) : boolean;
  8733. var
  8734. hp1: tai;
  8735. begin
  8736. { Detect:
  8737. shr x, %ax (x > 0)
  8738. ...
  8739. movzwl %ax,%eax
  8740. Change movzwl %ax,%eax to cwtl (shorter encoding for movswl %ax,%eax)
  8741. }
  8742. Result := False;
  8743. if MatchOpType(taicpu(p), top_const, top_reg) and
  8744. (taicpu(p).oper[1]^.reg = NR_AX) and { This is also enough to determine that opsize = S_W }
  8745. (taicpu(p).oper[0]^.val > 0) and
  8746. GetNextInstructionUsingReg(p, hp1, NR_EAX) and
  8747. MatchInstruction(hp1, A_MOVZX, [S_WL]) and
  8748. MatchOperand(taicpu(hp1).oper[0]^, NR_AX) and
  8749. MatchOperand(taicpu(hp1).oper[1]^, NR_EAX) then
  8750. begin
  8751. DebugMsg(SPeepholeOptimization + 'Converted movzwl %ax,%eax to cwtl (via ShrMovz2ShrCwtl)', hp1);
  8752. taicpu(hp1).opcode := A_CWDE;
  8753. taicpu(hp1).clearop(0);
  8754. taicpu(hp1).clearop(1);
  8755. taicpu(hp1).ops := 0;
  8756. { A change was made, but not with p, so move forward 1 }
  8757. p := tai(p.Next);
  8758. Result := True;
  8759. end;
  8760. end;
  8761. function TX86AsmOptimizer.PostPeepholeOptCmp(var p : tai) : Boolean;
  8762. begin
  8763. Result:=false;
  8764. { change "cmp $0, %reg" to "test %reg, %reg" }
  8765. if MatchOpType(taicpu(p),top_const,top_reg) and
  8766. (taicpu(p).oper[0]^.val = 0) then
  8767. begin
  8768. taicpu(p).opcode := A_TEST;
  8769. taicpu(p).loadreg(0,taicpu(p).oper[1]^.reg);
  8770. Result:=true;
  8771. end;
  8772. end;
  8773. function TX86AsmOptimizer.PostPeepholeOptTestOr(var p : tai) : Boolean;
  8774. var
  8775. IsTestConstX : Boolean;
  8776. hp1,hp2 : tai;
  8777. begin
  8778. Result:=false;
  8779. { removes the line marked with (x) from the sequence
  8780. and/or/xor/add/sub/... $x, %y
  8781. test/or %y, %y | test $-1, %y (x)
  8782. j(n)z _Label
  8783. as the first instruction already adjusts the ZF
  8784. %y operand may also be a reference }
  8785. IsTestConstX:=(taicpu(p).opcode=A_TEST) and
  8786. MatchOperand(taicpu(p).oper[0]^,-1);
  8787. if (OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) or IsTestConstX) and
  8788. GetLastInstruction(p, hp1) and
  8789. (tai(hp1).typ = ait_instruction) and
  8790. GetNextInstruction(p,hp2) and
  8791. MatchInstruction(hp2,A_SETcc,A_Jcc,A_CMOVcc,[]) then
  8792. case taicpu(hp1).opcode Of
  8793. A_ADD, A_SUB, A_OR, A_XOR, A_AND:
  8794. begin
  8795. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  8796. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  8797. { and in case of carry for A(E)/B(E)/C/NC }
  8798. ((taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) or
  8799. ((taicpu(hp1).opcode <> A_ADD) and
  8800. (taicpu(hp1).opcode <> A_SUB))) then
  8801. begin
  8802. RemoveCurrentP(p, hp2);
  8803. Result:=true;
  8804. Exit;
  8805. end;
  8806. end;
  8807. A_SHL, A_SAL, A_SHR, A_SAR:
  8808. begin
  8809. if OpsEqual(taicpu(hp1).oper[1]^,taicpu(p).oper[1]^) and
  8810. { SHL/SAL/SHR/SAR with a value of 0 do not change the flags }
  8811. { therefore, it's only safe to do this optimization for }
  8812. { shifts by a (nonzero) constant }
  8813. (taicpu(hp1).oper[0]^.typ = top_const) and
  8814. (taicpu(hp1).oper[0]^.val <> 0) and
  8815. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  8816. { and in case of carry for A(E)/B(E)/C/NC }
  8817. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  8818. begin
  8819. RemoveCurrentP(p, hp2);
  8820. Result:=true;
  8821. Exit;
  8822. end;
  8823. end;
  8824. A_DEC, A_INC, A_NEG:
  8825. begin
  8826. if OpsEqual(taicpu(hp1).oper[0]^,taicpu(p).oper[1]^) and
  8827. { does not work in case of overflow for G(E)/L(E)/C_O/C_NO }
  8828. { and in case of carry for A(E)/B(E)/C/NC }
  8829. (taicpu(hp2).condition in [C_Z,C_NZ,C_E,C_NE]) then
  8830. begin
  8831. case taicpu(hp1).opcode of
  8832. A_DEC, A_INC:
  8833. { replace inc/dec with add/sub 1, because inc/dec doesn't set the carry flag }
  8834. begin
  8835. case taicpu(hp1).opcode Of
  8836. A_DEC: taicpu(hp1).opcode := A_SUB;
  8837. A_INC: taicpu(hp1).opcode := A_ADD;
  8838. else
  8839. ;
  8840. end;
  8841. taicpu(hp1).loadoper(1,taicpu(hp1).oper[0]^);
  8842. taicpu(hp1).loadConst(0,1);
  8843. taicpu(hp1).ops:=2;
  8844. end;
  8845. else
  8846. ;
  8847. end;
  8848. RemoveCurrentP(p, hp2);
  8849. Result:=true;
  8850. Exit;
  8851. end;
  8852. end
  8853. else
  8854. ;
  8855. end; { case }
  8856. { change "test $-1,%reg" into "test %reg,%reg" }
  8857. if IsTestConstX and (taicpu(p).oper[1]^.typ=top_reg) then
  8858. taicpu(p).loadoper(0,taicpu(p).oper[1]^);
  8859. { Change "or %reg,%reg" to "test %reg,%reg" as OR generates a false dependency }
  8860. if MatchInstruction(p, A_OR, []) and
  8861. { Can only match if they're both registers }
  8862. MatchOperand(taicpu(p).oper[0]^, taicpu(p).oper[1]^) then
  8863. begin
  8864. DebugMsg(SPeepholeOptimization + 'or %reg,%reg -> test %reg,%reg to remove false dependency (Or2Test)', p);
  8865. taicpu(p).opcode := A_TEST;
  8866. { No need to set Result to True, as we've done all the optimisations we can }
  8867. end;
  8868. end;
  8869. function TX86AsmOptimizer.PostPeepholeOptCall(var p : tai) : Boolean;
  8870. var
  8871. hp1,hp3 : tai;
  8872. {$ifndef x86_64}
  8873. hp2 : taicpu;
  8874. {$endif x86_64}
  8875. begin
  8876. Result:=false;
  8877. hp3:=nil;
  8878. {$ifndef x86_64}
  8879. { don't do this on modern CPUs, this really hurts them due to
  8880. broken call/ret pairing }
  8881. if (current_settings.optimizecputype < cpu_Pentium2) and
  8882. not(cs_create_pic in current_settings.moduleswitches) and
  8883. GetNextInstruction(p, hp1) and
  8884. MatchInstruction(hp1,A_JMP,[S_NO]) and
  8885. MatchOpType(taicpu(hp1),top_ref) and
  8886. (taicpu(hp1).oper[0]^.ref^.refaddr=addr_full) then
  8887. begin
  8888. hp2 := taicpu.Op_sym(A_PUSH,S_L,taicpu(hp1).oper[0]^.ref^.symbol);
  8889. InsertLLItem(p.previous, p, hp2);
  8890. taicpu(p).opcode := A_JMP;
  8891. taicpu(p).is_jmp := true;
  8892. RemoveInstruction(hp1);
  8893. Result:=true;
  8894. end
  8895. else
  8896. {$endif x86_64}
  8897. { replace
  8898. call procname
  8899. ret
  8900. by
  8901. jmp procname
  8902. but do it only on level 4 because it destroys stack back traces
  8903. else if the subroutine is marked as no return, remove the ret
  8904. }
  8905. if ((cs_opt_level4 in current_settings.optimizerswitches) or
  8906. (po_noreturn in current_procinfo.procdef.procoptions)) and
  8907. GetNextInstruction(p, hp1) and
  8908. (MatchInstruction(hp1,A_RET,[S_NO]) or
  8909. (MatchInstruction(hp1,A_VZEROUPPER,[S_NO]) and
  8910. SetAndTest(hp1,hp3) and
  8911. GetNextInstruction(hp1,hp1) and
  8912. MatchInstruction(hp1,A_RET,[S_NO])
  8913. )
  8914. ) and
  8915. (taicpu(hp1).ops=0) then
  8916. begin
  8917. if (cs_opt_level4 in current_settings.optimizerswitches) and
  8918. { we might destroy stack alignment here if we do not do a call }
  8919. (target_info.stackalign<=sizeof(SizeUInt)) then
  8920. begin
  8921. taicpu(p).opcode := A_JMP;
  8922. taicpu(p).is_jmp := true;
  8923. DebugMsg(SPeepholeOptimization + 'CallRet2Jmp done',p);
  8924. end
  8925. else
  8926. DebugMsg(SPeepholeOptimization + 'CallRet2Call done',p);
  8927. RemoveInstruction(hp1);
  8928. if Assigned(hp3) then
  8929. begin
  8930. AsmL.Remove(hp3);
  8931. AsmL.InsertBefore(hp3,p)
  8932. end;
  8933. Result:=true;
  8934. end;
  8935. end;
  8936. function TX86AsmOptimizer.PostPeepholeOptMovzx(var p : tai) : Boolean;
  8937. function ConstInRange(const Val: TCGInt; const OpSize: TOpSize): Boolean;
  8938. begin
  8939. case OpSize of
  8940. S_B, S_BW, S_BL{$ifdef x86_64}, S_BQ{$endif x86_64}:
  8941. Result := (Val <= $FF) and (Val >= -128);
  8942. S_W, S_WL{$ifdef x86_64}, S_WQ{$endif x86_64}:
  8943. Result := (Val <= $FFFF) and (Val >= -32768);
  8944. S_L{$ifdef x86_64}, S_LQ{$endif x86_64}:
  8945. Result := (Val <= $FFFFFFFF) and (Val >= -2147483648);
  8946. else
  8947. Result := True;
  8948. end;
  8949. end;
  8950. var
  8951. hp1, hp2 : tai;
  8952. SizeChange: Boolean;
  8953. PreMessage: string;
  8954. begin
  8955. Result := False;
  8956. if (taicpu(p).oper[0]^.typ = top_reg) and
  8957. SuperRegistersEqual(taicpu(p).oper[0]^.reg, taicpu(p).oper[1]^.reg) and
  8958. GetNextInstruction(p, hp1) and (hp1.typ = ait_instruction) then
  8959. begin
  8960. { Change (using movzbl %al,%eax as an example):
  8961. movzbl %al, %eax movzbl %al, %eax
  8962. cmpl x, %eax testl %eax,%eax
  8963. To:
  8964. cmpb x, %al testb %al, %al (Move one back to avoid a false dependency)
  8965. movzbl %al, %eax movzbl %al, %eax
  8966. Smaller instruction and minimises pipeline stall as the CPU
  8967. doesn't have to wait for the register to get zero-extended. [Kit]
  8968. Also allow if the smaller of the two registers is being checked,
  8969. as this still removes the false dependency.
  8970. }
  8971. if
  8972. (
  8973. (
  8974. (taicpu(hp1).opcode = A_CMP) and MatchOpType(taicpu(hp1), top_const, top_reg) and
  8975. ConstInRange(taicpu(hp1).oper[0]^.val, taicpu(p).opsize)
  8976. ) or (
  8977. { If MatchOperand returns True, they must both be registers }
  8978. (taicpu(hp1).opcode = A_TEST) and MatchOperand(taicpu(hp1).oper[0]^, taicpu(hp1).oper[1]^)
  8979. )
  8980. ) and
  8981. (reg2opsize(taicpu(hp1).oper[1]^.reg) <= reg2opsize(taicpu(p).oper[1]^.reg)) and
  8982. SuperRegistersEqual(taicpu(p).oper[1]^.reg, taicpu(hp1).oper[1]^.reg) then
  8983. begin
  8984. 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);
  8985. asml.Remove(hp1);
  8986. asml.InsertBefore(hp1, p);
  8987. { Swap instructions in the case of cmp 0,%reg or test %reg,%reg }
  8988. if (taicpu(hp1).opcode = A_TEST) or (taicpu(hp1).oper[0]^.val = 0) then
  8989. begin
  8990. taicpu(hp1).opcode := A_TEST;
  8991. taicpu(hp1).loadreg(0, taicpu(p).oper[0]^.reg);
  8992. end;
  8993. taicpu(hp1).oper[1]^.reg := taicpu(p).oper[0]^.reg;
  8994. case taicpu(p).opsize of
  8995. S_BW, S_BL:
  8996. begin
  8997. SizeChange := taicpu(hp1).opsize <> S_B;
  8998. taicpu(hp1).changeopsize(S_B);
  8999. end;
  9000. S_WL:
  9001. begin
  9002. SizeChange := taicpu(hp1).opsize <> S_W;
  9003. taicpu(hp1).changeopsize(S_W);
  9004. end
  9005. else
  9006. InternalError(2020112701);
  9007. end;
  9008. UpdateUsedRegs(tai(p.Next));
  9009. { Check if the register is used aferwards - if not, we can
  9010. remove the movzx instruction completely }
  9011. if not RegUsedAfterInstruction(taicpu(hp1).oper[1]^.reg, p, UsedRegs) then
  9012. begin
  9013. { Hp1 is a better position than p for debugging purposes }
  9014. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4a', hp1);
  9015. RemoveCurrentp(p, hp1);
  9016. Result := True;
  9017. end;
  9018. if SizeChange then
  9019. DebugMsg(SPeepholeOptimization + PreMessage +
  9020. 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)
  9021. else
  9022. DebugMsg(SPeepholeOptimization + 'MovzxCmp2CmpMovzx', hp1);
  9023. Exit;
  9024. end;
  9025. { Change (using movzwl %ax,%eax as an example):
  9026. movzwl %ax, %eax
  9027. movb %al, (dest) (Register is smaller than read register in movz)
  9028. To:
  9029. movb %al, (dest) (Move one back to avoid a false dependency)
  9030. movzwl %ax, %eax
  9031. }
  9032. if (taicpu(hp1).opcode = A_MOV) and
  9033. (taicpu(hp1).oper[0]^.typ = top_reg) and
  9034. not RegInOp(taicpu(hp1).oper[0]^.reg, taicpu(hp1).oper[1]^) and
  9035. SuperRegistersEqual(taicpu(hp1).oper[0]^.reg, taicpu(p).oper[0]^.reg) and
  9036. (reg2opsize(taicpu(hp1).oper[0]^.reg) <= reg2opsize(taicpu(p).oper[0]^.reg)) then
  9037. begin
  9038. DebugMsg(SPeepholeOptimization + 'MovzxMov2MovMovzx', hp1);
  9039. hp2 := tai(hp1.Previous); { Effectively the old position of hp1 }
  9040. asml.Remove(hp1);
  9041. asml.InsertBefore(hp1, p);
  9042. if taicpu(hp1).oper[1]^.typ = top_reg then
  9043. AllocRegBetween(taicpu(hp1).oper[1]^.reg, hp1, hp2, UsedRegs);
  9044. { Check if the register is used aferwards - if not, we can
  9045. remove the movzx instruction completely }
  9046. if not RegUsedAfterInstruction(taicpu(hp1).oper[0]^.reg, p, UsedRegs) then
  9047. begin
  9048. { Hp1 is a better position than p for debugging purposes }
  9049. DebugMsg(SPeepholeOptimization + 'Movzx2Nop 4b', hp1);
  9050. RemoveCurrentp(p, hp1);
  9051. Result := True;
  9052. end;
  9053. Exit;
  9054. end;
  9055. end;
  9056. {$ifdef x86_64}
  9057. { Code size reduction by J. Gareth "Kit" Moreton }
  9058. { Convert MOVZBQ and MOVZWQ to MOVZBL and MOVZWL respectively if it removes the REX prefix }
  9059. if (taicpu(p).opsize in [S_BQ, S_WQ]) and
  9060. (getsupreg(taicpu(p).oper[1]^.reg) in [RS_RAX, RS_RCX, RS_RDX, RS_RBX, RS_RSI, RS_RDI, RS_RBP, RS_RSP])
  9061. then
  9062. begin
  9063. { Has 64-bit register name and opcode suffix }
  9064. PreMessage := 'movz' + debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' -> movz';
  9065. { The actual optimization }
  9066. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  9067. if taicpu(p).opsize = S_BQ then
  9068. taicpu(p).changeopsize(S_BL)
  9069. else
  9070. taicpu(p).changeopsize(S_WL);
  9071. DebugMsg(SPeepholeOptimization + PreMessage +
  9072. debug_opsize2str(taicpu(p).opsize) + ' ' + debug_operstr(taicpu(p).oper[0]^) + ',' + debug_regname(taicpu(p).oper[1]^.reg) + ' (removes REX prefix)', p);
  9073. end;
  9074. {$endif}
  9075. end;
  9076. {$ifdef x86_64}
  9077. function TX86AsmOptimizer.PostPeepholeOptXor(var p : tai) : Boolean;
  9078. var
  9079. PreMessage, RegName: string;
  9080. begin
  9081. { Code size reduction by J. Gareth "Kit" Moreton }
  9082. { change "xorq %reg,%reg" to "xorl %reg,%reg" for %rax, %rcx, %rdx, %rbx, %rsi, %rdi, %rbp and %rsp,
  9083. as this removes the REX prefix }
  9084. Result := False;
  9085. if not OpsEqual(taicpu(p).oper[0]^,taicpu(p).oper[1]^) then
  9086. Exit;
  9087. if taicpu(p).oper[0]^.typ <> top_reg then
  9088. { Should be impossible if both operands were equal, since one of XOR's operands must be a register }
  9089. InternalError(2018011500);
  9090. case taicpu(p).opsize of
  9091. S_Q:
  9092. begin
  9093. if (getsupreg(taicpu(p).oper[0]^.reg) in [RS_RAX, RS_RCX, RS_RDX, RS_RBX, RS_RSI, RS_RDI, RS_RBP, RS_RSP]) then
  9094. begin
  9095. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 64-bit register name }
  9096. PreMessage := 'xorq ' + RegName + ',' + RegName + ' -> xorl ';
  9097. { The actual optimization }
  9098. setsubreg(taicpu(p).oper[0]^.reg, R_SUBD);
  9099. setsubreg(taicpu(p).oper[1]^.reg, R_SUBD);
  9100. taicpu(p).changeopsize(S_L);
  9101. RegName := debug_regname(taicpu(p).oper[0]^.reg); { 32-bit register name }
  9102. DebugMsg(SPeepholeOptimization + PreMessage + RegName + ',' + RegName + ' (removes REX prefix)', p);
  9103. end;
  9104. end;
  9105. else
  9106. ;
  9107. end;
  9108. end;
  9109. {$endif}
  9110. class procedure TX86AsmOptimizer.OptimizeRefs(var p: taicpu);
  9111. var
  9112. OperIdx: Integer;
  9113. begin
  9114. for OperIdx := 0 to p.ops - 1 do
  9115. if p.oper[OperIdx]^.typ = top_ref then
  9116. optimize_ref(p.oper[OperIdx]^.ref^, False);
  9117. end;
  9118. end.