2
0

CodeGenPrepare.cpp 179 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832
  1. //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This pass munges the code in the input function to better prepare it for
  11. // SelectionDAG-based code generation. This works around limitations in it's
  12. // basic-block-at-a-time approach. It should eventually be removed.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/CodeGen/Passes.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/SmallSet.h"
  18. #include "llvm/ADT/Statistic.h"
  19. #include "llvm/Analysis/InstructionSimplify.h"
  20. #include "llvm/Analysis/TargetLibraryInfo.h"
  21. #include "llvm/Analysis/TargetTransformInfo.h"
  22. #include "llvm/IR/CallSite.h"
  23. #include "llvm/IR/Constants.h"
  24. #include "llvm/IR/DataLayout.h"
  25. #include "llvm/IR/DerivedTypes.h"
  26. #include "llvm/IR/Dominators.h"
  27. #include "llvm/IR/Function.h"
  28. #include "llvm/IR/GetElementPtrTypeIterator.h"
  29. #include "llvm/IR/IRBuilder.h"
  30. #include "llvm/IR/InlineAsm.h"
  31. #include "llvm/IR/Instructions.h"
  32. #include "llvm/IR/IntrinsicInst.h"
  33. #include "llvm/IR/MDBuilder.h"
  34. #include "llvm/IR/PatternMatch.h"
  35. #include "llvm/IR/Statepoint.h"
  36. #include "llvm/IR/ValueHandle.h"
  37. #include "llvm/IR/ValueMap.h"
  38. #include "llvm/Pass.h"
  39. #include "llvm/Support/CommandLine.h"
  40. #include "llvm/Support/Debug.h"
  41. #include "llvm/Support/raw_ostream.h"
  42. #include "llvm/Target/TargetLowering.h"
  43. #include "llvm/Target/TargetSubtargetInfo.h"
  44. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  45. #include "llvm/Transforms/Utils/BuildLibCalls.h"
  46. #include "llvm/Transforms/Utils/BypassSlowDivision.h"
  47. #include "llvm/Transforms/Utils/Local.h"
  48. #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
  49. using namespace llvm;
  50. using namespace llvm::PatternMatch;
  51. #define DEBUG_TYPE "codegenprepare"
  52. STATISTIC(NumBlocksElim, "Number of blocks eliminated");
  53. STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
  54. STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
  55. STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
  56. "sunken Cmps");
  57. STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
  58. "of sunken Casts");
  59. STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
  60. "computations were sunk");
  61. STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
  62. STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
  63. STATISTIC(NumRetsDup, "Number of return instructions duplicated");
  64. STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
  65. STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
  66. STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
  67. STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
  68. static cl::opt<bool> DisableBranchOpts(
  69. "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
  70. cl::desc("Disable branch optimizations in CodeGenPrepare"));
  71. static cl::opt<bool>
  72. DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
  73. cl::desc("Disable GC optimizations in CodeGenPrepare"));
  74. static cl::opt<bool> DisableSelectToBranch(
  75. "disable-cgp-select2branch", cl::Hidden, cl::init(false),
  76. cl::desc("Disable select to branch conversion."));
  77. static cl::opt<bool> AddrSinkUsingGEPs(
  78. "addr-sink-using-gep", cl::Hidden, cl::init(false),
  79. cl::desc("Address sinking in CGP using GEPs."));
  80. static cl::opt<bool> EnableAndCmpSinking(
  81. "enable-andcmp-sinking", cl::Hidden, cl::init(true),
  82. cl::desc("Enable sinkinig and/cmp into branches."));
  83. static cl::opt<bool> DisableStoreExtract(
  84. "disable-cgp-store-extract", cl::Hidden, cl::init(false),
  85. cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
  86. static cl::opt<bool> StressStoreExtract(
  87. "stress-cgp-store-extract", cl::Hidden, cl::init(false),
  88. cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
  89. static cl::opt<bool> DisableExtLdPromotion(
  90. "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
  91. cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
  92. "CodeGenPrepare"));
  93. static cl::opt<bool> StressExtLdPromotion(
  94. "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
  95. cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
  96. "optimization in CodeGenPrepare"));
  97. namespace {
  98. typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
  99. struct TypeIsSExt {
  100. Type *Ty;
  101. bool IsSExt;
  102. TypeIsSExt(Type *Ty, bool IsSExt) : Ty(Ty), IsSExt(IsSExt) {}
  103. };
  104. typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
  105. class TypePromotionTransaction;
  106. class CodeGenPrepare : public FunctionPass {
  107. /// TLI - Keep a pointer of a TargetLowering to consult for determining
  108. /// transformation profitability.
  109. const TargetMachine *TM;
  110. const TargetLowering *TLI;
  111. const TargetTransformInfo *TTI;
  112. const TargetLibraryInfo *TLInfo;
  113. /// CurInstIterator - As we scan instructions optimizing them, this is the
  114. /// next instruction to optimize. Xforms that can invalidate this should
  115. /// update it.
  116. BasicBlock::iterator CurInstIterator;
  117. /// Keeps track of non-local addresses that have been sunk into a block.
  118. /// This allows us to avoid inserting duplicate code for blocks with
  119. /// multiple load/stores of the same address.
  120. ValueMap<Value*, Value*> SunkAddrs;
  121. /// Keeps track of all instructions inserted for the current function.
  122. SetOfInstrs InsertedInsts;
  123. /// Keeps track of the type of the related instruction before their
  124. /// promotion for the current function.
  125. InstrToOrigTy PromotedInsts;
  126. /// ModifiedDT - If CFG is modified in anyway.
  127. bool ModifiedDT;
  128. /// OptSize - True if optimizing for size.
  129. bool OptSize;
  130. /// DataLayout for the Function being processed.
  131. const DataLayout *DL;
  132. public:
  133. static char ID; // Pass identification, replacement for typeid
  134. explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
  135. : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
  136. initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
  137. }
  138. bool runOnFunction(Function &F) override;
  139. const char *getPassName() const override { return "CodeGen Prepare"; }
  140. void getAnalysisUsage(AnalysisUsage &AU) const override {
  141. AU.addPreserved<DominatorTreeWrapperPass>();
  142. AU.addRequired<TargetLibraryInfoWrapperPass>();
  143. AU.addRequired<TargetTransformInfoWrapperPass>();
  144. }
  145. private:
  146. bool EliminateFallThrough(Function &F);
  147. bool EliminateMostlyEmptyBlocks(Function &F);
  148. bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
  149. void EliminateMostlyEmptyBlock(BasicBlock *BB);
  150. bool OptimizeBlock(BasicBlock &BB, bool& ModifiedDT);
  151. bool OptimizeInst(Instruction *I, bool& ModifiedDT);
  152. bool OptimizeMemoryInst(Instruction *I, Value *Addr,
  153. Type *AccessTy, unsigned AS);
  154. bool OptimizeInlineAsmInst(CallInst *CS);
  155. bool OptimizeCallInst(CallInst *CI, bool& ModifiedDT);
  156. bool MoveExtToFormExtLoad(Instruction *&I);
  157. bool OptimizeExtUses(Instruction *I);
  158. bool OptimizeSelectInst(SelectInst *SI);
  159. bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
  160. bool OptimizeExtractElementInst(Instruction *Inst);
  161. bool DupRetToEnableTailCallOpts(BasicBlock *BB);
  162. bool PlaceDbgValues(Function &F);
  163. bool sinkAndCmp(Function &F);
  164. bool ExtLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
  165. Instruction *&Inst,
  166. const SmallVectorImpl<Instruction *> &Exts,
  167. unsigned CreatedInstCost);
  168. bool splitBranchCondition(Function &F);
  169. bool simplifyOffsetableRelocate(Instruction &I);
  170. };
  171. }
  172. char CodeGenPrepare::ID = 0;
  173. INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
  174. "Optimize for code generation", false, false)
  175. FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
  176. return new CodeGenPrepare(TM);
  177. }
  178. bool CodeGenPrepare::runOnFunction(Function &F) {
  179. if (skipOptnoneFunction(F))
  180. return false;
  181. DL = &F.getParent()->getDataLayout();
  182. bool EverMadeChange = false;
  183. // Clear per function information.
  184. InsertedInsts.clear();
  185. PromotedInsts.clear();
  186. ModifiedDT = false;
  187. if (TM)
  188. TLI = TM->getSubtargetImpl(F)->getTargetLowering();
  189. TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  190. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  191. OptSize = F.hasFnAttribute(Attribute::OptimizeForSize);
  192. /// This optimization identifies DIV instructions that can be
  193. /// profitably bypassed and carried out with a shorter, faster divide.
  194. if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
  195. const DenseMap<unsigned int, unsigned int> &BypassWidths =
  196. TLI->getBypassSlowDivWidths();
  197. for (Function::iterator I = F.begin(); I != F.end(); I++)
  198. EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
  199. }
  200. // Eliminate blocks that contain only PHI nodes and an
  201. // unconditional branch.
  202. EverMadeChange |= EliminateMostlyEmptyBlocks(F);
  203. // llvm.dbg.value is far away from the value then iSel may not be able
  204. // handle it properly. iSel will drop llvm.dbg.value if it can not
  205. // find a node corresponding to the value.
  206. EverMadeChange |= PlaceDbgValues(F);
  207. // If there is a mask, compare against zero, and branch that can be combined
  208. // into a single target instruction, push the mask and compare into branch
  209. // users. Do this before OptimizeBlock -> OptimizeInst ->
  210. // OptimizeCmpExpression, which perturbs the pattern being searched for.
  211. if (!DisableBranchOpts) {
  212. EverMadeChange |= sinkAndCmp(F);
  213. EverMadeChange |= splitBranchCondition(F);
  214. }
  215. bool MadeChange = true;
  216. while (MadeChange) {
  217. MadeChange = false;
  218. for (Function::iterator I = F.begin(); I != F.end(); ) {
  219. BasicBlock *BB = I++;
  220. bool ModifiedDTOnIteration = false;
  221. MadeChange |= OptimizeBlock(*BB, ModifiedDTOnIteration);
  222. // Restart BB iteration if the dominator tree of the Function was changed
  223. if (ModifiedDTOnIteration)
  224. break;
  225. }
  226. EverMadeChange |= MadeChange;
  227. }
  228. SunkAddrs.clear();
  229. if (!DisableBranchOpts) {
  230. MadeChange = false;
  231. SmallPtrSet<BasicBlock*, 8> WorkList;
  232. for (BasicBlock &BB : F) {
  233. SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
  234. MadeChange |= ConstantFoldTerminator(&BB, true);
  235. if (!MadeChange) continue;
  236. for (SmallVectorImpl<BasicBlock*>::iterator
  237. II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
  238. if (pred_begin(*II) == pred_end(*II))
  239. WorkList.insert(*II);
  240. }
  241. // Delete the dead blocks and any of their dead successors.
  242. MadeChange |= !WorkList.empty();
  243. while (!WorkList.empty()) {
  244. BasicBlock *BB = *WorkList.begin();
  245. WorkList.erase(BB);
  246. SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
  247. DeleteDeadBlock(BB);
  248. for (SmallVectorImpl<BasicBlock*>::iterator
  249. II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
  250. if (pred_begin(*II) == pred_end(*II))
  251. WorkList.insert(*II);
  252. }
  253. // Merge pairs of basic blocks with unconditional branches, connected by
  254. // a single edge.
  255. if (EverMadeChange || MadeChange)
  256. MadeChange |= EliminateFallThrough(F);
  257. EverMadeChange |= MadeChange;
  258. }
  259. if (!DisableGCOpts) {
  260. SmallVector<Instruction *, 2> Statepoints;
  261. for (BasicBlock &BB : F)
  262. for (Instruction &I : BB)
  263. if (isStatepoint(I))
  264. Statepoints.push_back(&I);
  265. for (auto &I : Statepoints)
  266. EverMadeChange |= simplifyOffsetableRelocate(*I);
  267. }
  268. return EverMadeChange;
  269. }
  270. /// EliminateFallThrough - Merge basic blocks which are connected
  271. /// by a single edge, where one of the basic blocks has a single successor
  272. /// pointing to the other basic block, which has a single predecessor.
  273. bool CodeGenPrepare::EliminateFallThrough(Function &F) {
  274. bool Changed = false;
  275. // Scan all of the blocks in the function, except for the entry block.
  276. for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
  277. BasicBlock *BB = I++;
  278. // If the destination block has a single pred, then this is a trivial
  279. // edge, just collapse it.
  280. BasicBlock *SinglePred = BB->getSinglePredecessor();
  281. // Don't merge if BB's address is taken.
  282. if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
  283. BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
  284. if (Term && !Term->isConditional()) {
  285. Changed = true;
  286. DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
  287. // Remember if SinglePred was the entry block of the function.
  288. // If so, we will need to move BB back to the entry position.
  289. bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
  290. MergeBasicBlockIntoOnlyPred(BB, nullptr);
  291. if (isEntry && BB != &BB->getParent()->getEntryBlock())
  292. BB->moveBefore(&BB->getParent()->getEntryBlock());
  293. // We have erased a block. Update the iterator.
  294. I = BB;
  295. }
  296. }
  297. return Changed;
  298. }
  299. /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
  300. /// debug info directives, and an unconditional branch. Passes before isel
  301. /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
  302. /// isel. Start by eliminating these blocks so we can split them the way we
  303. /// want them.
  304. bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
  305. bool MadeChange = false;
  306. // Note that this intentionally skips the entry block.
  307. for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
  308. BasicBlock *BB = I++;
  309. // If this block doesn't end with an uncond branch, ignore it.
  310. BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
  311. if (!BI || !BI->isUnconditional())
  312. continue;
  313. // If the instruction before the branch (skipping debug info) isn't a phi
  314. // node, then other stuff is happening here.
  315. BasicBlock::iterator BBI = BI;
  316. if (BBI != BB->begin()) {
  317. --BBI;
  318. while (isa<DbgInfoIntrinsic>(BBI)) {
  319. if (BBI == BB->begin())
  320. break;
  321. --BBI;
  322. }
  323. if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
  324. continue;
  325. }
  326. // Do not break infinite loops.
  327. BasicBlock *DestBB = BI->getSuccessor(0);
  328. if (DestBB == BB)
  329. continue;
  330. if (!CanMergeBlocks(BB, DestBB))
  331. continue;
  332. EliminateMostlyEmptyBlock(BB);
  333. MadeChange = true;
  334. }
  335. return MadeChange;
  336. }
  337. /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
  338. /// single uncond branch between them, and BB contains no other non-phi
  339. /// instructions.
  340. bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
  341. const BasicBlock *DestBB) const {
  342. // We only want to eliminate blocks whose phi nodes are used by phi nodes in
  343. // the successor. If there are more complex condition (e.g. preheaders),
  344. // don't mess around with them.
  345. BasicBlock::const_iterator BBI = BB->begin();
  346. while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
  347. for (const User *U : PN->users()) {
  348. const Instruction *UI = cast<Instruction>(U);
  349. if (UI->getParent() != DestBB || !isa<PHINode>(UI))
  350. return false;
  351. // If User is inside DestBB block and it is a PHINode then check
  352. // incoming value. If incoming value is not from BB then this is
  353. // a complex condition (e.g. preheaders) we want to avoid here.
  354. if (UI->getParent() == DestBB) {
  355. if (const PHINode *UPN = dyn_cast<PHINode>(UI))
  356. for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
  357. Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
  358. if (Insn && Insn->getParent() == BB &&
  359. Insn->getParent() != UPN->getIncomingBlock(I))
  360. return false;
  361. }
  362. }
  363. }
  364. }
  365. // If BB and DestBB contain any common predecessors, then the phi nodes in BB
  366. // and DestBB may have conflicting incoming values for the block. If so, we
  367. // can't merge the block.
  368. const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
  369. if (!DestBBPN) return true; // no conflict.
  370. // Collect the preds of BB.
  371. SmallPtrSet<const BasicBlock*, 16> BBPreds;
  372. if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
  373. // It is faster to get preds from a PHI than with pred_iterator.
  374. for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
  375. BBPreds.insert(BBPN->getIncomingBlock(i));
  376. } else {
  377. BBPreds.insert(pred_begin(BB), pred_end(BB));
  378. }
  379. // Walk the preds of DestBB.
  380. for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
  381. BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
  382. if (BBPreds.count(Pred)) { // Common predecessor?
  383. BBI = DestBB->begin();
  384. while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
  385. const Value *V1 = PN->getIncomingValueForBlock(Pred);
  386. const Value *V2 = PN->getIncomingValueForBlock(BB);
  387. // If V2 is a phi node in BB, look up what the mapped value will be.
  388. if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
  389. if (V2PN->getParent() == BB)
  390. V2 = V2PN->getIncomingValueForBlock(Pred);
  391. // If there is a conflict, bail out.
  392. if (V1 != V2) return false;
  393. }
  394. }
  395. }
  396. return true;
  397. }
  398. /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
  399. /// an unconditional branch in it.
  400. void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
  401. BranchInst *BI = cast<BranchInst>(BB->getTerminator());
  402. BasicBlock *DestBB = BI->getSuccessor(0);
  403. DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
  404. // If the destination block has a single pred, then this is a trivial edge,
  405. // just collapse it.
  406. if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
  407. if (SinglePred != DestBB) {
  408. // Remember if SinglePred was the entry block of the function. If so, we
  409. // will need to move BB back to the entry position.
  410. bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
  411. MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
  412. if (isEntry && BB != &BB->getParent()->getEntryBlock())
  413. BB->moveBefore(&BB->getParent()->getEntryBlock());
  414. DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
  415. return;
  416. }
  417. }
  418. // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
  419. // to handle the new incoming edges it is about to have.
  420. PHINode *PN;
  421. for (BasicBlock::iterator BBI = DestBB->begin();
  422. (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
  423. // Remove the incoming value for BB, and remember it.
  424. Value *InVal = PN->removeIncomingValue(BB, false);
  425. // Two options: either the InVal is a phi node defined in BB or it is some
  426. // value that dominates BB.
  427. PHINode *InValPhi = dyn_cast<PHINode>(InVal);
  428. if (InValPhi && InValPhi->getParent() == BB) {
  429. // Add all of the input values of the input PHI as inputs of this phi.
  430. for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
  431. PN->addIncoming(InValPhi->getIncomingValue(i),
  432. InValPhi->getIncomingBlock(i));
  433. } else {
  434. // Otherwise, add one instance of the dominating value for each edge that
  435. // we will be adding.
  436. if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
  437. for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
  438. PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
  439. } else {
  440. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  441. PN->addIncoming(InVal, *PI);
  442. }
  443. }
  444. }
  445. // The PHIs are now updated, change everything that refers to BB to use
  446. // DestBB and remove BB.
  447. BB->replaceAllUsesWith(DestBB);
  448. BB->eraseFromParent();
  449. ++NumBlocksElim;
  450. DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
  451. }
  452. // Computes a map of base pointer relocation instructions to corresponding
  453. // derived pointer relocation instructions given a vector of all relocate calls
  454. static void computeBaseDerivedRelocateMap(
  455. const SmallVectorImpl<User *> &AllRelocateCalls,
  456. DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> &
  457. RelocateInstMap) {
  458. // Collect information in two maps: one primarily for locating the base object
  459. // while filling the second map; the second map is the final structure holding
  460. // a mapping between Base and corresponding Derived relocate calls
  461. DenseMap<std::pair<unsigned, unsigned>, IntrinsicInst *> RelocateIdxMap;
  462. for (auto &U : AllRelocateCalls) {
  463. GCRelocateOperands ThisRelocate(U);
  464. IntrinsicInst *I = cast<IntrinsicInst>(U);
  465. auto K = std::make_pair(ThisRelocate.getBasePtrIndex(),
  466. ThisRelocate.getDerivedPtrIndex());
  467. RelocateIdxMap.insert(std::make_pair(K, I));
  468. }
  469. for (auto &Item : RelocateIdxMap) {
  470. std::pair<unsigned, unsigned> Key = Item.first;
  471. if (Key.first == Key.second)
  472. // Base relocation: nothing to insert
  473. continue;
  474. IntrinsicInst *I = Item.second;
  475. auto BaseKey = std::make_pair(Key.first, Key.first);
  476. // We're iterating over RelocateIdxMap so we cannot modify it.
  477. auto MaybeBase = RelocateIdxMap.find(BaseKey);
  478. if (MaybeBase == RelocateIdxMap.end())
  479. // TODO: We might want to insert a new base object relocate and gep off
  480. // that, if there are enough derived object relocates.
  481. continue;
  482. RelocateInstMap[MaybeBase->second].push_back(I);
  483. }
  484. }
  485. // Accepts a GEP and extracts the operands into a vector provided they're all
  486. // small integer constants
  487. static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
  488. SmallVectorImpl<Value *> &OffsetV) {
  489. for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
  490. // Only accept small constant integer operands
  491. auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
  492. if (!Op || Op->getZExtValue() > 20)
  493. return false;
  494. }
  495. for (unsigned i = 1; i < GEP->getNumOperands(); i++)
  496. OffsetV.push_back(GEP->getOperand(i));
  497. return true;
  498. }
  499. // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
  500. // replace, computes a replacement, and affects it.
  501. static bool
  502. simplifyRelocatesOffABase(IntrinsicInst *RelocatedBase,
  503. const SmallVectorImpl<IntrinsicInst *> &Targets) {
  504. bool MadeChange = false;
  505. for (auto &ToReplace : Targets) {
  506. GCRelocateOperands MasterRelocate(RelocatedBase);
  507. GCRelocateOperands ThisRelocate(ToReplace);
  508. assert(ThisRelocate.getBasePtrIndex() == MasterRelocate.getBasePtrIndex() &&
  509. "Not relocating a derived object of the original base object");
  510. if (ThisRelocate.getBasePtrIndex() == ThisRelocate.getDerivedPtrIndex()) {
  511. // A duplicate relocate call. TODO: coalesce duplicates.
  512. continue;
  513. }
  514. Value *Base = ThisRelocate.getBasePtr();
  515. auto Derived = dyn_cast<GetElementPtrInst>(ThisRelocate.getDerivedPtr());
  516. if (!Derived || Derived->getPointerOperand() != Base)
  517. continue;
  518. SmallVector<Value *, 2> OffsetV;
  519. if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
  520. continue;
  521. // Create a Builder and replace the target callsite with a gep
  522. assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator");
  523. // Insert after RelocatedBase
  524. IRBuilder<> Builder(RelocatedBase->getNextNode());
  525. Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
  526. // If gc_relocate does not match the actual type, cast it to the right type.
  527. // In theory, there must be a bitcast after gc_relocate if the type does not
  528. // match, and we should reuse it to get the derived pointer. But it could be
  529. // cases like this:
  530. // bb1:
  531. // ...
  532. // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
  533. // br label %merge
  534. //
  535. // bb2:
  536. // ...
  537. // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
  538. // br label %merge
  539. //
  540. // merge:
  541. // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
  542. // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
  543. //
  544. // In this case, we can not find the bitcast any more. So we insert a new bitcast
  545. // no matter there is already one or not. In this way, we can handle all cases, and
  546. // the extra bitcast should be optimized away in later passes.
  547. Instruction *ActualRelocatedBase = RelocatedBase;
  548. if (RelocatedBase->getType() != Base->getType()) {
  549. ActualRelocatedBase =
  550. cast<Instruction>(Builder.CreateBitCast(RelocatedBase, Base->getType()));
  551. }
  552. Value *Replacement = Builder.CreateGEP(
  553. Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
  554. Instruction *ReplacementInst = cast<Instruction>(Replacement);
  555. Replacement->takeName(ToReplace);
  556. // If the newly generated derived pointer's type does not match the original derived
  557. // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
  558. Instruction *ActualReplacement = ReplacementInst;
  559. if (ReplacementInst->getType() != ToReplace->getType()) {
  560. ActualReplacement =
  561. cast<Instruction>(Builder.CreateBitCast(ReplacementInst, ToReplace->getType()));
  562. }
  563. ToReplace->replaceAllUsesWith(ActualReplacement);
  564. ToReplace->eraseFromParent();
  565. MadeChange = true;
  566. }
  567. return MadeChange;
  568. }
  569. // Turns this:
  570. //
  571. // %base = ...
  572. // %ptr = gep %base + 15
  573. // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
  574. // %base' = relocate(%tok, i32 4, i32 4)
  575. // %ptr' = relocate(%tok, i32 4, i32 5)
  576. // %val = load %ptr'
  577. //
  578. // into this:
  579. //
  580. // %base = ...
  581. // %ptr = gep %base + 15
  582. // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
  583. // %base' = gc.relocate(%tok, i32 4, i32 4)
  584. // %ptr' = gep %base' + 15
  585. // %val = load %ptr'
  586. bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
  587. bool MadeChange = false;
  588. SmallVector<User *, 2> AllRelocateCalls;
  589. for (auto *U : I.users())
  590. if (isGCRelocate(dyn_cast<Instruction>(U)))
  591. // Collect all the relocate calls associated with a statepoint
  592. AllRelocateCalls.push_back(U);
  593. // We need atleast one base pointer relocation + one derived pointer
  594. // relocation to mangle
  595. if (AllRelocateCalls.size() < 2)
  596. return false;
  597. // RelocateInstMap is a mapping from the base relocate instruction to the
  598. // corresponding derived relocate instructions
  599. DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> RelocateInstMap;
  600. computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
  601. if (RelocateInstMap.empty())
  602. return false;
  603. for (auto &Item : RelocateInstMap)
  604. // Item.first is the RelocatedBase to offset against
  605. // Item.second is the vector of Targets to replace
  606. MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
  607. return MadeChange;
  608. }
  609. /// SinkCast - Sink the specified cast instruction into its user blocks
  610. static bool SinkCast(CastInst *CI) {
  611. BasicBlock *DefBB = CI->getParent();
  612. /// InsertedCasts - Only insert a cast in each block once.
  613. DenseMap<BasicBlock*, CastInst*> InsertedCasts;
  614. bool MadeChange = false;
  615. for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
  616. UI != E; ) {
  617. Use &TheUse = UI.getUse();
  618. Instruction *User = cast<Instruction>(*UI);
  619. // Figure out which BB this cast is used in. For PHI's this is the
  620. // appropriate predecessor block.
  621. BasicBlock *UserBB = User->getParent();
  622. if (PHINode *PN = dyn_cast<PHINode>(User)) {
  623. UserBB = PN->getIncomingBlock(TheUse);
  624. }
  625. // Preincrement use iterator so we don't invalidate it.
  626. ++UI;
  627. // If this user is in the same block as the cast, don't change the cast.
  628. if (UserBB == DefBB) continue;
  629. // If we have already inserted a cast into this block, use it.
  630. CastInst *&InsertedCast = InsertedCasts[UserBB];
  631. if (!InsertedCast) {
  632. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  633. InsertedCast =
  634. CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
  635. InsertPt);
  636. }
  637. // Replace a use of the cast with a use of the new cast.
  638. TheUse = InsertedCast;
  639. MadeChange = true;
  640. ++NumCastUses;
  641. }
  642. // If we removed all uses, nuke the cast.
  643. if (CI->use_empty()) {
  644. CI->eraseFromParent();
  645. MadeChange = true;
  646. }
  647. return MadeChange;
  648. }
  649. /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
  650. /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
  651. /// sink it into user blocks to reduce the number of virtual
  652. /// registers that must be created and coalesced.
  653. ///
  654. /// Return true if any changes are made.
  655. ///
  656. static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
  657. const DataLayout &DL) {
  658. // If this is a noop copy,
  659. EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
  660. EVT DstVT = TLI.getValueType(DL, CI->getType());
  661. // This is an fp<->int conversion?
  662. if (SrcVT.isInteger() != DstVT.isInteger())
  663. return false;
  664. // If this is an extension, it will be a zero or sign extension, which
  665. // isn't a noop.
  666. if (SrcVT.bitsLT(DstVT)) return false;
  667. // If these values will be promoted, find out what they will be promoted
  668. // to. This helps us consider truncates on PPC as noop copies when they
  669. // are.
  670. if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
  671. TargetLowering::TypePromoteInteger)
  672. SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
  673. if (TLI.getTypeAction(CI->getContext(), DstVT) ==
  674. TargetLowering::TypePromoteInteger)
  675. DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
  676. // If, after promotion, these are the same types, this is a noop copy.
  677. if (SrcVT != DstVT)
  678. return false;
  679. return SinkCast(CI);
  680. }
  681. /// CombineUAddWithOverflow - try to combine CI into a call to the
  682. /// llvm.uadd.with.overflow intrinsic if possible.
  683. ///
  684. /// Return true if any changes were made.
  685. static bool CombineUAddWithOverflow(CmpInst *CI) {
  686. Value *A, *B;
  687. Instruction *AddI;
  688. if (!match(CI,
  689. m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
  690. return false;
  691. Type *Ty = AddI->getType();
  692. if (!isa<IntegerType>(Ty))
  693. return false;
  694. // We don't want to move around uses of condition values this late, so we we
  695. // check if it is legal to create the call to the intrinsic in the basic
  696. // block containing the icmp:
  697. if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
  698. return false;
  699. #ifndef NDEBUG
  700. // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
  701. // for now:
  702. if (AddI->hasOneUse())
  703. assert(*AddI->user_begin() == CI && "expected!");
  704. #endif
  705. Module *M = CI->getParent()->getParent()->getParent();
  706. Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
  707. auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
  708. auto *UAddWithOverflow =
  709. CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
  710. auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
  711. auto *Overflow =
  712. ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
  713. CI->replaceAllUsesWith(Overflow);
  714. AddI->replaceAllUsesWith(UAdd);
  715. CI->eraseFromParent();
  716. AddI->eraseFromParent();
  717. return true;
  718. }
  719. /// SinkCmpExpression - Sink the given CmpInst into user blocks to reduce
  720. /// the number of virtual registers that must be created and coalesced. This is
  721. /// a clear win except on targets with multiple condition code registers
  722. /// (PowerPC), where it might lose; some adjustment may be wanted there.
  723. ///
  724. /// Return true if any changes are made.
  725. static bool SinkCmpExpression(CmpInst *CI) {
  726. BasicBlock *DefBB = CI->getParent();
  727. /// InsertedCmp - Only insert a cmp in each block once.
  728. DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
  729. bool MadeChange = false;
  730. for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
  731. UI != E; ) {
  732. Use &TheUse = UI.getUse();
  733. Instruction *User = cast<Instruction>(*UI);
  734. // Preincrement use iterator so we don't invalidate it.
  735. ++UI;
  736. // Don't bother for PHI nodes.
  737. if (isa<PHINode>(User))
  738. continue;
  739. // Figure out which BB this cmp is used in.
  740. BasicBlock *UserBB = User->getParent();
  741. // If this user is in the same block as the cmp, don't change the cmp.
  742. if (UserBB == DefBB) continue;
  743. // If we have already inserted a cmp into this block, use it.
  744. CmpInst *&InsertedCmp = InsertedCmps[UserBB];
  745. if (!InsertedCmp) {
  746. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  747. InsertedCmp =
  748. CmpInst::Create(CI->getOpcode(),
  749. CI->getPredicate(), CI->getOperand(0),
  750. CI->getOperand(1), "", InsertPt);
  751. }
  752. // Replace a use of the cmp with a use of the new cmp.
  753. TheUse = InsertedCmp;
  754. MadeChange = true;
  755. ++NumCmpUses;
  756. }
  757. // If we removed all uses, nuke the cmp.
  758. if (CI->use_empty()) {
  759. CI->eraseFromParent();
  760. MadeChange = true;
  761. }
  762. return MadeChange;
  763. }
  764. static bool OptimizeCmpExpression(CmpInst *CI) {
  765. if (SinkCmpExpression(CI))
  766. return true;
  767. if (CombineUAddWithOverflow(CI))
  768. return true;
  769. return false;
  770. }
  771. /// isExtractBitsCandidateUse - Check if the candidates could
  772. /// be combined with shift instruction, which includes:
  773. /// 1. Truncate instruction
  774. /// 2. And instruction and the imm is a mask of the low bits:
  775. /// imm & (imm+1) == 0
  776. static bool isExtractBitsCandidateUse(Instruction *User) {
  777. if (!isa<TruncInst>(User)) {
  778. if (User->getOpcode() != Instruction::And ||
  779. !isa<ConstantInt>(User->getOperand(1)))
  780. return false;
  781. const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
  782. if ((Cimm & (Cimm + 1)).getBoolValue())
  783. return false;
  784. }
  785. return true;
  786. }
  787. /// SinkShiftAndTruncate - sink both shift and truncate instruction
  788. /// to the use of truncate's BB.
  789. static bool
  790. SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
  791. DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
  792. const TargetLowering &TLI, const DataLayout &DL) {
  793. BasicBlock *UserBB = User->getParent();
  794. DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
  795. TruncInst *TruncI = dyn_cast<TruncInst>(User);
  796. bool MadeChange = false;
  797. for (Value::user_iterator TruncUI = TruncI->user_begin(),
  798. TruncE = TruncI->user_end();
  799. TruncUI != TruncE;) {
  800. Use &TruncTheUse = TruncUI.getUse();
  801. Instruction *TruncUser = cast<Instruction>(*TruncUI);
  802. // Preincrement use iterator so we don't invalidate it.
  803. ++TruncUI;
  804. int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
  805. if (!ISDOpcode)
  806. continue;
  807. // If the use is actually a legal node, there will not be an
  808. // implicit truncate.
  809. // FIXME: always querying the result type is just an
  810. // approximation; some nodes' legality is determined by the
  811. // operand or other means. There's no good way to find out though.
  812. if (TLI.isOperationLegalOrCustom(
  813. ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
  814. continue;
  815. // Don't bother for PHI nodes.
  816. if (isa<PHINode>(TruncUser))
  817. continue;
  818. BasicBlock *TruncUserBB = TruncUser->getParent();
  819. if (UserBB == TruncUserBB)
  820. continue;
  821. BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
  822. CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
  823. if (!InsertedShift && !InsertedTrunc) {
  824. BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
  825. // Sink the shift
  826. if (ShiftI->getOpcode() == Instruction::AShr)
  827. InsertedShift =
  828. BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
  829. else
  830. InsertedShift =
  831. BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
  832. // Sink the trunc
  833. BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
  834. TruncInsertPt++;
  835. InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
  836. TruncI->getType(), "", TruncInsertPt);
  837. MadeChange = true;
  838. TruncTheUse = InsertedTrunc;
  839. }
  840. }
  841. return MadeChange;
  842. }
  843. /// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
  844. /// the uses could potentially be combined with this shift instruction and
  845. /// generate BitExtract instruction. It will only be applied if the architecture
  846. /// supports BitExtract instruction. Here is an example:
  847. /// BB1:
  848. /// %x.extract.shift = lshr i64 %arg1, 32
  849. /// BB2:
  850. /// %x.extract.trunc = trunc i64 %x.extract.shift to i16
  851. /// ==>
  852. ///
  853. /// BB2:
  854. /// %x.extract.shift.1 = lshr i64 %arg1, 32
  855. /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
  856. ///
  857. /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
  858. /// instruction.
  859. /// Return true if any changes are made.
  860. static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
  861. const TargetLowering &TLI,
  862. const DataLayout &DL) {
  863. BasicBlock *DefBB = ShiftI->getParent();
  864. /// Only insert instructions in each block once.
  865. DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
  866. bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
  867. bool MadeChange = false;
  868. for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
  869. UI != E;) {
  870. Use &TheUse = UI.getUse();
  871. Instruction *User = cast<Instruction>(*UI);
  872. // Preincrement use iterator so we don't invalidate it.
  873. ++UI;
  874. // Don't bother for PHI nodes.
  875. if (isa<PHINode>(User))
  876. continue;
  877. if (!isExtractBitsCandidateUse(User))
  878. continue;
  879. BasicBlock *UserBB = User->getParent();
  880. if (UserBB == DefBB) {
  881. // If the shift and truncate instruction are in the same BB. The use of
  882. // the truncate(TruncUse) may still introduce another truncate if not
  883. // legal. In this case, we would like to sink both shift and truncate
  884. // instruction to the BB of TruncUse.
  885. // for example:
  886. // BB1:
  887. // i64 shift.result = lshr i64 opnd, imm
  888. // trunc.result = trunc shift.result to i16
  889. //
  890. // BB2:
  891. // ----> We will have an implicit truncate here if the architecture does
  892. // not have i16 compare.
  893. // cmp i16 trunc.result, opnd2
  894. //
  895. if (isa<TruncInst>(User) && shiftIsLegal
  896. // If the type of the truncate is legal, no trucate will be
  897. // introduced in other basic blocks.
  898. &&
  899. (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
  900. MadeChange =
  901. SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
  902. continue;
  903. }
  904. // If we have already inserted a shift into this block, use it.
  905. BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
  906. if (!InsertedShift) {
  907. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  908. if (ShiftI->getOpcode() == Instruction::AShr)
  909. InsertedShift =
  910. BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
  911. else
  912. InsertedShift =
  913. BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
  914. MadeChange = true;
  915. }
  916. // Replace a use of the shift with a use of the new shift.
  917. TheUse = InsertedShift;
  918. }
  919. // If we removed all uses, nuke the shift.
  920. if (ShiftI->use_empty())
  921. ShiftI->eraseFromParent();
  922. return MadeChange;
  923. }
  924. // ScalarizeMaskedLoad() translates masked load intrinsic, like
  925. // <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
  926. // <16 x i1> %mask, <16 x i32> %passthru)
  927. // to a chain of basic blocks, whith loading element one-by-one if
  928. // the appropriate mask bit is set
  929. //
  930. // %1 = bitcast i8* %addr to i32*
  931. // %2 = extractelement <16 x i1> %mask, i32 0
  932. // %3 = icmp eq i1 %2, true
  933. // br i1 %3, label %cond.load, label %else
  934. //
  935. //cond.load: ; preds = %0
  936. // %4 = getelementptr i32* %1, i32 0
  937. // %5 = load i32* %4
  938. // %6 = insertelement <16 x i32> undef, i32 %5, i32 0
  939. // br label %else
  940. //
  941. //else: ; preds = %0, %cond.load
  942. // %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
  943. // %7 = extractelement <16 x i1> %mask, i32 1
  944. // %8 = icmp eq i1 %7, true
  945. // br i1 %8, label %cond.load1, label %else2
  946. //
  947. //cond.load1: ; preds = %else
  948. // %9 = getelementptr i32* %1, i32 1
  949. // %10 = load i32* %9
  950. // %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
  951. // br label %else2
  952. //
  953. //else2: ; preds = %else, %cond.load1
  954. // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
  955. // %12 = extractelement <16 x i1> %mask, i32 2
  956. // %13 = icmp eq i1 %12, true
  957. // br i1 %13, label %cond.load4, label %else5
  958. //
  959. static void ScalarizeMaskedLoad(CallInst *CI) {
  960. Value *Ptr = CI->getArgOperand(0);
  961. Value *Src0 = CI->getArgOperand(3);
  962. Value *Mask = CI->getArgOperand(2);
  963. VectorType *VecType = dyn_cast<VectorType>(CI->getType());
  964. Type *EltTy = VecType->getElementType();
  965. assert(VecType && "Unexpected return type of masked load intrinsic");
  966. IRBuilder<> Builder(CI->getContext());
  967. Instruction *InsertPt = CI;
  968. BasicBlock *IfBlock = CI->getParent();
  969. BasicBlock *CondBlock = nullptr;
  970. BasicBlock *PrevIfBlock = CI->getParent();
  971. Builder.SetInsertPoint(InsertPt);
  972. Builder.SetCurrentDebugLocation(CI->getDebugLoc());
  973. // Bitcast %addr fron i8* to EltTy*
  974. Type *NewPtrType =
  975. EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
  976. Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
  977. Value *UndefVal = UndefValue::get(VecType);
  978. // The result vector
  979. Value *VResult = UndefVal;
  980. PHINode *Phi = nullptr;
  981. Value *PrevPhi = UndefVal;
  982. unsigned VectorWidth = VecType->getNumElements();
  983. for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
  984. // Fill the "else" block, created in the previous iteration
  985. //
  986. // %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
  987. // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
  988. // %to_load = icmp eq i1 %mask_1, true
  989. // br i1 %to_load, label %cond.load, label %else
  990. //
  991. if (Idx > 0) {
  992. Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
  993. Phi->addIncoming(VResult, CondBlock);
  994. Phi->addIncoming(PrevPhi, PrevIfBlock);
  995. PrevPhi = Phi;
  996. VResult = Phi;
  997. }
  998. Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
  999. Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
  1000. ConstantInt::get(Predicate->getType(), 1));
  1001. // Create "cond" block
  1002. //
  1003. // %EltAddr = getelementptr i32* %1, i32 0
  1004. // %Elt = load i32* %EltAddr
  1005. // VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
  1006. //
  1007. CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
  1008. Builder.SetInsertPoint(InsertPt);
  1009. Value *Gep =
  1010. Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
  1011. LoadInst* Load = Builder.CreateLoad(Gep, false);
  1012. VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
  1013. // Create "else" block, fill it in the next iteration
  1014. BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
  1015. Builder.SetInsertPoint(InsertPt);
  1016. Instruction *OldBr = IfBlock->getTerminator();
  1017. BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
  1018. OldBr->eraseFromParent();
  1019. PrevIfBlock = IfBlock;
  1020. IfBlock = NewIfBlock;
  1021. }
  1022. Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
  1023. Phi->addIncoming(VResult, CondBlock);
  1024. Phi->addIncoming(PrevPhi, PrevIfBlock);
  1025. Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
  1026. CI->replaceAllUsesWith(NewI);
  1027. CI->eraseFromParent();
  1028. }
  1029. // ScalarizeMaskedStore() translates masked store intrinsic, like
  1030. // void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
  1031. // <16 x i1> %mask)
  1032. // to a chain of basic blocks, that stores element one-by-one if
  1033. // the appropriate mask bit is set
  1034. //
  1035. // %1 = bitcast i8* %addr to i32*
  1036. // %2 = extractelement <16 x i1> %mask, i32 0
  1037. // %3 = icmp eq i1 %2, true
  1038. // br i1 %3, label %cond.store, label %else
  1039. //
  1040. // cond.store: ; preds = %0
  1041. // %4 = extractelement <16 x i32> %val, i32 0
  1042. // %5 = getelementptr i32* %1, i32 0
  1043. // store i32 %4, i32* %5
  1044. // br label %else
  1045. //
  1046. // else: ; preds = %0, %cond.store
  1047. // %6 = extractelement <16 x i1> %mask, i32 1
  1048. // %7 = icmp eq i1 %6, true
  1049. // br i1 %7, label %cond.store1, label %else2
  1050. //
  1051. // cond.store1: ; preds = %else
  1052. // %8 = extractelement <16 x i32> %val, i32 1
  1053. // %9 = getelementptr i32* %1, i32 1
  1054. // store i32 %8, i32* %9
  1055. // br label %else2
  1056. // . . .
  1057. static void ScalarizeMaskedStore(CallInst *CI) {
  1058. Value *Ptr = CI->getArgOperand(1);
  1059. Value *Src = CI->getArgOperand(0);
  1060. Value *Mask = CI->getArgOperand(3);
  1061. VectorType *VecType = dyn_cast<VectorType>(Src->getType());
  1062. Type *EltTy = VecType->getElementType();
  1063. assert(VecType && "Unexpected data type in masked store intrinsic");
  1064. IRBuilder<> Builder(CI->getContext());
  1065. Instruction *InsertPt = CI;
  1066. BasicBlock *IfBlock = CI->getParent();
  1067. Builder.SetInsertPoint(InsertPt);
  1068. Builder.SetCurrentDebugLocation(CI->getDebugLoc());
  1069. // Bitcast %addr fron i8* to EltTy*
  1070. Type *NewPtrType =
  1071. EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
  1072. Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
  1073. unsigned VectorWidth = VecType->getNumElements();
  1074. for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
  1075. // Fill the "else" block, created in the previous iteration
  1076. //
  1077. // %mask_1 = extractelement <16 x i1> %mask, i32 Idx
  1078. // %to_store = icmp eq i1 %mask_1, true
  1079. // br i1 %to_load, label %cond.store, label %else
  1080. //
  1081. Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
  1082. Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
  1083. ConstantInt::get(Predicate->getType(), 1));
  1084. // Create "cond" block
  1085. //
  1086. // %OneElt = extractelement <16 x i32> %Src, i32 Idx
  1087. // %EltAddr = getelementptr i32* %1, i32 0
  1088. // %store i32 %OneElt, i32* %EltAddr
  1089. //
  1090. BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
  1091. Builder.SetInsertPoint(InsertPt);
  1092. Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
  1093. Value *Gep =
  1094. Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
  1095. Builder.CreateStore(OneElt, Gep);
  1096. // Create "else" block, fill it in the next iteration
  1097. BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
  1098. Builder.SetInsertPoint(InsertPt);
  1099. Instruction *OldBr = IfBlock->getTerminator();
  1100. BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
  1101. OldBr->eraseFromParent();
  1102. IfBlock = NewIfBlock;
  1103. }
  1104. CI->eraseFromParent();
  1105. }
  1106. bool CodeGenPrepare::OptimizeCallInst(CallInst *CI, bool& ModifiedDT) {
  1107. BasicBlock *BB = CI->getParent();
  1108. // Lower inline assembly if we can.
  1109. // If we found an inline asm expession, and if the target knows how to
  1110. // lower it to normal LLVM code, do so now.
  1111. if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
  1112. if (TLI->ExpandInlineAsm(CI)) {
  1113. // Avoid invalidating the iterator.
  1114. CurInstIterator = BB->begin();
  1115. // Avoid processing instructions out of order, which could cause
  1116. // reuse before a value is defined.
  1117. SunkAddrs.clear();
  1118. return true;
  1119. }
  1120. // Sink address computing for memory operands into the block.
  1121. if (OptimizeInlineAsmInst(CI))
  1122. return true;
  1123. }
  1124. // Align the pointer arguments to this call if the target thinks it's a good
  1125. // idea
  1126. unsigned MinSize, PrefAlign;
  1127. if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
  1128. for (auto &Arg : CI->arg_operands()) {
  1129. // We want to align both objects whose address is used directly and
  1130. // objects whose address is used in casts and GEPs, though it only makes
  1131. // sense for GEPs if the offset is a multiple of the desired alignment and
  1132. // if size - offset meets the size threshold.
  1133. if (!Arg->getType()->isPointerTy())
  1134. continue;
  1135. APInt Offset(DL->getPointerSizeInBits(
  1136. cast<PointerType>(Arg->getType())->getAddressSpace()),
  1137. 0);
  1138. Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
  1139. uint64_t Offset2 = Offset.getLimitedValue();
  1140. if ((Offset2 & (PrefAlign-1)) != 0)
  1141. continue;
  1142. AllocaInst *AI;
  1143. if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
  1144. DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
  1145. AI->setAlignment(PrefAlign);
  1146. // Global variables can only be aligned if they are defined in this
  1147. // object (i.e. they are uniquely initialized in this object), and
  1148. // over-aligning global variables that have an explicit section is
  1149. // forbidden.
  1150. GlobalVariable *GV;
  1151. if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->hasUniqueInitializer() &&
  1152. !GV->hasSection() && GV->getAlignment() < PrefAlign &&
  1153. DL->getTypeAllocSize(GV->getType()->getElementType()) >=
  1154. MinSize + Offset2)
  1155. GV->setAlignment(PrefAlign);
  1156. }
  1157. // If this is a memcpy (or similar) then we may be able to improve the
  1158. // alignment
  1159. if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
  1160. unsigned Align = getKnownAlignment(MI->getDest(), *DL);
  1161. if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
  1162. Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
  1163. if (Align > MI->getAlignment())
  1164. MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
  1165. }
  1166. }
  1167. IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
  1168. if (II) {
  1169. switch (II->getIntrinsicID()) {
  1170. default: break;
  1171. case Intrinsic::objectsize: {
  1172. // Lower all uses of llvm.objectsize.*
  1173. bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
  1174. Type *ReturnTy = CI->getType();
  1175. Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
  1176. // Substituting this can cause recursive simplifications, which can
  1177. // invalidate our iterator. Use a WeakVH to hold onto it in case this
  1178. // happens.
  1179. WeakVH IterHandle(CurInstIterator);
  1180. replaceAndRecursivelySimplify(CI, RetVal,
  1181. TLInfo, nullptr);
  1182. // If the iterator instruction was recursively deleted, start over at the
  1183. // start of the block.
  1184. if (IterHandle != CurInstIterator) {
  1185. CurInstIterator = BB->begin();
  1186. SunkAddrs.clear();
  1187. }
  1188. return true;
  1189. }
  1190. case Intrinsic::masked_load: {
  1191. // Scalarize unsupported vector masked load
  1192. if (!TTI->isLegalMaskedLoad(CI->getType(), 1)) {
  1193. ScalarizeMaskedLoad(CI);
  1194. ModifiedDT = true;
  1195. return true;
  1196. }
  1197. return false;
  1198. }
  1199. case Intrinsic::masked_store: {
  1200. if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType(), 1)) {
  1201. ScalarizeMaskedStore(CI);
  1202. ModifiedDT = true;
  1203. return true;
  1204. }
  1205. return false;
  1206. }
  1207. #if 0 // HLSL Change - remove platform intrinsics
  1208. case Intrinsic::aarch64_stlxr:
  1209. case Intrinsic::aarch64_stxr: {
  1210. ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
  1211. if (!ExtVal || !ExtVal->hasOneUse() ||
  1212. ExtVal->getParent() == CI->getParent())
  1213. return false;
  1214. // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
  1215. ExtVal->moveBefore(CI);
  1216. // Mark this instruction as "inserted by CGP", so that other
  1217. // optimizations don't touch it.
  1218. InsertedInsts.insert(ExtVal);
  1219. return true;
  1220. }
  1221. #endif // HLSL Change - remove platform intrinsics
  1222. }
  1223. if (TLI) {
  1224. // Unknown address space.
  1225. // TODO: Target hook to pick which address space the intrinsic cares
  1226. // about?
  1227. unsigned AddrSpace = ~0u;
  1228. SmallVector<Value*, 2> PtrOps;
  1229. Type *AccessTy;
  1230. if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
  1231. while (!PtrOps.empty())
  1232. if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
  1233. return true;
  1234. }
  1235. }
  1236. // From here on out we're working with named functions.
  1237. if (!CI->getCalledFunction()) return false;
  1238. // Lower all default uses of _chk calls. This is very similar
  1239. // to what InstCombineCalls does, but here we are only lowering calls
  1240. // to fortified library functions (e.g. __memcpy_chk) that have the default
  1241. // "don't know" as the objectsize. Anything else should be left alone.
  1242. FortifiedLibCallSimplifier Simplifier(TLInfo, true);
  1243. if (Value *V = Simplifier.optimizeCall(CI)) {
  1244. CI->replaceAllUsesWith(V);
  1245. CI->eraseFromParent();
  1246. return true;
  1247. }
  1248. return false;
  1249. }
  1250. /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
  1251. /// instructions to the predecessor to enable tail call optimizations. The
  1252. /// case it is currently looking for is:
  1253. /// @code
  1254. /// bb0:
  1255. /// %tmp0 = tail call i32 @f0()
  1256. /// br label %return
  1257. /// bb1:
  1258. /// %tmp1 = tail call i32 @f1()
  1259. /// br label %return
  1260. /// bb2:
  1261. /// %tmp2 = tail call i32 @f2()
  1262. /// br label %return
  1263. /// return:
  1264. /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
  1265. /// ret i32 %retval
  1266. /// @endcode
  1267. ///
  1268. /// =>
  1269. ///
  1270. /// @code
  1271. /// bb0:
  1272. /// %tmp0 = tail call i32 @f0()
  1273. /// ret i32 %tmp0
  1274. /// bb1:
  1275. /// %tmp1 = tail call i32 @f1()
  1276. /// ret i32 %tmp1
  1277. /// bb2:
  1278. /// %tmp2 = tail call i32 @f2()
  1279. /// ret i32 %tmp2
  1280. /// @endcode
  1281. bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
  1282. if (!TLI)
  1283. return false;
  1284. ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
  1285. if (!RI)
  1286. return false;
  1287. PHINode *PN = nullptr;
  1288. BitCastInst *BCI = nullptr;
  1289. Value *V = RI->getReturnValue();
  1290. if (V) {
  1291. BCI = dyn_cast<BitCastInst>(V);
  1292. if (BCI)
  1293. V = BCI->getOperand(0);
  1294. PN = dyn_cast<PHINode>(V);
  1295. if (!PN)
  1296. return false;
  1297. }
  1298. if (PN && PN->getParent() != BB)
  1299. return false;
  1300. // It's not safe to eliminate the sign / zero extension of the return value.
  1301. // See llvm::isInTailCallPosition().
  1302. const Function *F = BB->getParent();
  1303. AttributeSet CallerAttrs = F->getAttributes();
  1304. if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
  1305. CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
  1306. return false;
  1307. // Make sure there are no instructions between the PHI and return, or that the
  1308. // return is the first instruction in the block.
  1309. if (PN) {
  1310. BasicBlock::iterator BI = BB->begin();
  1311. do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
  1312. if (&*BI == BCI)
  1313. // Also skip over the bitcast.
  1314. ++BI;
  1315. if (&*BI != RI)
  1316. return false;
  1317. } else {
  1318. BasicBlock::iterator BI = BB->begin();
  1319. while (isa<DbgInfoIntrinsic>(BI)) ++BI;
  1320. if (&*BI != RI)
  1321. return false;
  1322. }
  1323. /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
  1324. /// call.
  1325. SmallVector<CallInst*, 4> TailCalls;
  1326. if (PN) {
  1327. for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
  1328. CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
  1329. // Make sure the phi value is indeed produced by the tail call.
  1330. if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
  1331. TLI->mayBeEmittedAsTailCall(CI))
  1332. TailCalls.push_back(CI);
  1333. }
  1334. } else {
  1335. SmallPtrSet<BasicBlock*, 4> VisitedBBs;
  1336. for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
  1337. if (!VisitedBBs.insert(*PI).second)
  1338. continue;
  1339. BasicBlock::InstListType &InstList = (*PI)->getInstList();
  1340. BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
  1341. BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
  1342. do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
  1343. if (RI == RE)
  1344. continue;
  1345. CallInst *CI = dyn_cast<CallInst>(&*RI);
  1346. if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
  1347. TailCalls.push_back(CI);
  1348. }
  1349. }
  1350. bool Changed = false;
  1351. for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
  1352. CallInst *CI = TailCalls[i];
  1353. CallSite CS(CI);
  1354. // Conservatively require the attributes of the call to match those of the
  1355. // return. Ignore noalias because it doesn't affect the call sequence.
  1356. AttributeSet CalleeAttrs = CS.getAttributes();
  1357. if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
  1358. removeAttribute(Attribute::NoAlias) !=
  1359. AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
  1360. removeAttribute(Attribute::NoAlias))
  1361. continue;
  1362. // Make sure the call instruction is followed by an unconditional branch to
  1363. // the return block.
  1364. BasicBlock *CallBB = CI->getParent();
  1365. BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
  1366. if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
  1367. continue;
  1368. // Duplicate the return into CallBB.
  1369. (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
  1370. ModifiedDT = Changed = true;
  1371. ++NumRetsDup;
  1372. }
  1373. // If we eliminated all predecessors of the block, delete the block now.
  1374. if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
  1375. BB->eraseFromParent();
  1376. return Changed;
  1377. }
  1378. //===----------------------------------------------------------------------===//
  1379. // Memory Optimization
  1380. //===----------------------------------------------------------------------===//
  1381. namespace {
  1382. /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
  1383. /// which holds actual Value*'s for register values.
  1384. struct ExtAddrMode : public TargetLowering::AddrMode {
  1385. Value *BaseReg;
  1386. Value *ScaledReg;
  1387. ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
  1388. void print(raw_ostream &OS) const;
  1389. void dump() const;
  1390. bool operator==(const ExtAddrMode& O) const {
  1391. return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
  1392. (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
  1393. (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
  1394. }
  1395. };
  1396. #ifndef NDEBUG
  1397. static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
  1398. AM.print(OS);
  1399. return OS;
  1400. }
  1401. #endif
  1402. void ExtAddrMode::print(raw_ostream &OS) const {
  1403. bool NeedPlus = false;
  1404. OS << "[";
  1405. if (BaseGV) {
  1406. OS << (NeedPlus ? " + " : "")
  1407. << "GV:";
  1408. BaseGV->printAsOperand(OS, /*PrintType=*/false);
  1409. NeedPlus = true;
  1410. }
  1411. if (BaseOffs) {
  1412. OS << (NeedPlus ? " + " : "")
  1413. << BaseOffs;
  1414. NeedPlus = true;
  1415. }
  1416. if (BaseReg) {
  1417. OS << (NeedPlus ? " + " : "")
  1418. << "Base:";
  1419. BaseReg->printAsOperand(OS, /*PrintType=*/false);
  1420. NeedPlus = true;
  1421. }
  1422. if (Scale) {
  1423. OS << (NeedPlus ? " + " : "")
  1424. << Scale << "*";
  1425. ScaledReg->printAsOperand(OS, /*PrintType=*/false);
  1426. }
  1427. OS << ']';
  1428. }
  1429. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1430. void ExtAddrMode::dump() const {
  1431. print(dbgs());
  1432. dbgs() << '\n';
  1433. }
  1434. #endif
  1435. /// \brief This class provides transaction based operation on the IR.
  1436. /// Every change made through this class is recorded in the internal state and
  1437. /// can be undone (rollback) until commit is called.
  1438. class TypePromotionTransaction {
  1439. /// \brief This represents the common interface of the individual transaction.
  1440. /// Each class implements the logic for doing one specific modification on
  1441. /// the IR via the TypePromotionTransaction.
  1442. class TypePromotionAction {
  1443. protected:
  1444. /// The Instruction modified.
  1445. Instruction *Inst;
  1446. public:
  1447. /// \brief Constructor of the action.
  1448. /// The constructor performs the related action on the IR.
  1449. TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
  1450. virtual ~TypePromotionAction() {}
  1451. /// \brief Undo the modification done by this action.
  1452. /// When this method is called, the IR must be in the same state as it was
  1453. /// before this action was applied.
  1454. /// \pre Undoing the action works if and only if the IR is in the exact same
  1455. /// state as it was directly after this action was applied.
  1456. virtual void undo() = 0;
  1457. /// \brief Advocate every change made by this action.
  1458. /// When the results on the IR of the action are to be kept, it is important
  1459. /// to call this function, otherwise hidden information may be kept forever.
  1460. virtual void commit() {
  1461. // Nothing to be done, this action is not doing anything.
  1462. }
  1463. };
  1464. /// \brief Utility to remember the position of an instruction.
  1465. class InsertionHandler {
  1466. /// Position of an instruction.
  1467. /// Either an instruction:
  1468. /// - Is the first in a basic block: BB is used.
  1469. /// - Has a previous instructon: PrevInst is used.
  1470. union {
  1471. Instruction *PrevInst;
  1472. BasicBlock *BB;
  1473. } Point;
  1474. /// Remember whether or not the instruction had a previous instruction.
  1475. bool HasPrevInstruction;
  1476. public:
  1477. /// \brief Record the position of \p Inst.
  1478. InsertionHandler(Instruction *Inst) {
  1479. BasicBlock::iterator It = Inst;
  1480. HasPrevInstruction = (It != (Inst->getParent()->begin()));
  1481. if (HasPrevInstruction)
  1482. Point.PrevInst = --It;
  1483. else
  1484. Point.BB = Inst->getParent();
  1485. }
  1486. /// \brief Insert \p Inst at the recorded position.
  1487. void insert(Instruction *Inst) {
  1488. if (HasPrevInstruction) {
  1489. if (Inst->getParent())
  1490. Inst->removeFromParent();
  1491. Inst->insertAfter(Point.PrevInst);
  1492. } else {
  1493. Instruction *Position = Point.BB->getFirstInsertionPt();
  1494. if (Inst->getParent())
  1495. Inst->moveBefore(Position);
  1496. else
  1497. Inst->insertBefore(Position);
  1498. }
  1499. }
  1500. };
  1501. /// \brief Move an instruction before another.
  1502. class InstructionMoveBefore : public TypePromotionAction {
  1503. /// Original position of the instruction.
  1504. InsertionHandler Position;
  1505. public:
  1506. /// \brief Move \p Inst before \p Before.
  1507. InstructionMoveBefore(Instruction *Inst, Instruction *Before)
  1508. : TypePromotionAction(Inst), Position(Inst) {
  1509. DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
  1510. Inst->moveBefore(Before);
  1511. }
  1512. /// \brief Move the instruction back to its original position.
  1513. void undo() override {
  1514. DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
  1515. Position.insert(Inst);
  1516. }
  1517. };
  1518. /// \brief Set the operand of an instruction with a new value.
  1519. class OperandSetter : public TypePromotionAction {
  1520. /// Original operand of the instruction.
  1521. Value *Origin;
  1522. /// Index of the modified instruction.
  1523. unsigned Idx;
  1524. public:
  1525. /// \brief Set \p Idx operand of \p Inst with \p NewVal.
  1526. OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
  1527. : TypePromotionAction(Inst), Idx(Idx) {
  1528. DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
  1529. << "for:" << *Inst << "\n"
  1530. << "with:" << *NewVal << "\n");
  1531. Origin = Inst->getOperand(Idx);
  1532. Inst->setOperand(Idx, NewVal);
  1533. }
  1534. /// \brief Restore the original value of the instruction.
  1535. void undo() override {
  1536. DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
  1537. << "for: " << *Inst << "\n"
  1538. << "with: " << *Origin << "\n");
  1539. Inst->setOperand(Idx, Origin);
  1540. }
  1541. };
  1542. /// \brief Hide the operands of an instruction.
  1543. /// Do as if this instruction was not using any of its operands.
  1544. class OperandsHider : public TypePromotionAction {
  1545. /// The list of original operands.
  1546. SmallVector<Value *, 4> OriginalValues;
  1547. public:
  1548. /// \brief Remove \p Inst from the uses of the operands of \p Inst.
  1549. OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
  1550. DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
  1551. unsigned NumOpnds = Inst->getNumOperands();
  1552. OriginalValues.reserve(NumOpnds);
  1553. for (unsigned It = 0; It < NumOpnds; ++It) {
  1554. // Save the current operand.
  1555. Value *Val = Inst->getOperand(It);
  1556. OriginalValues.push_back(Val);
  1557. // Set a dummy one.
  1558. // We could use OperandSetter here, but that would implied an overhead
  1559. // that we are not willing to pay.
  1560. Inst->setOperand(It, UndefValue::get(Val->getType()));
  1561. }
  1562. }
  1563. /// \brief Restore the original list of uses.
  1564. void undo() override {
  1565. DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
  1566. for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
  1567. Inst->setOperand(It, OriginalValues[It]);
  1568. }
  1569. };
  1570. /// \brief Build a truncate instruction.
  1571. class TruncBuilder : public TypePromotionAction {
  1572. Value *Val;
  1573. public:
  1574. /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
  1575. /// result.
  1576. /// trunc Opnd to Ty.
  1577. TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
  1578. IRBuilder<> Builder(Opnd);
  1579. Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
  1580. DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
  1581. }
  1582. /// \brief Get the built value.
  1583. Value *getBuiltValue() { return Val; }
  1584. /// \brief Remove the built instruction.
  1585. void undo() override {
  1586. DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
  1587. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  1588. IVal->eraseFromParent();
  1589. }
  1590. };
  1591. /// \brief Build a sign extension instruction.
  1592. class SExtBuilder : public TypePromotionAction {
  1593. Value *Val;
  1594. public:
  1595. /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
  1596. /// result.
  1597. /// sext Opnd to Ty.
  1598. SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
  1599. : TypePromotionAction(InsertPt) {
  1600. IRBuilder<> Builder(InsertPt);
  1601. Val = Builder.CreateSExt(Opnd, Ty, "promoted");
  1602. DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
  1603. }
  1604. /// \brief Get the built value.
  1605. Value *getBuiltValue() { return Val; }
  1606. /// \brief Remove the built instruction.
  1607. void undo() override {
  1608. DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
  1609. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  1610. IVal->eraseFromParent();
  1611. }
  1612. };
  1613. /// \brief Build a zero extension instruction.
  1614. class ZExtBuilder : public TypePromotionAction {
  1615. Value *Val;
  1616. public:
  1617. /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
  1618. /// result.
  1619. /// zext Opnd to Ty.
  1620. ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
  1621. : TypePromotionAction(InsertPt) {
  1622. IRBuilder<> Builder(InsertPt);
  1623. Val = Builder.CreateZExt(Opnd, Ty, "promoted");
  1624. DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
  1625. }
  1626. /// \brief Get the built value.
  1627. Value *getBuiltValue() { return Val; }
  1628. /// \brief Remove the built instruction.
  1629. void undo() override {
  1630. DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
  1631. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  1632. IVal->eraseFromParent();
  1633. }
  1634. };
  1635. /// \brief Mutate an instruction to another type.
  1636. class TypeMutator : public TypePromotionAction {
  1637. /// Record the original type.
  1638. Type *OrigTy;
  1639. public:
  1640. /// \brief Mutate the type of \p Inst into \p NewTy.
  1641. TypeMutator(Instruction *Inst, Type *NewTy)
  1642. : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
  1643. DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
  1644. << "\n");
  1645. Inst->mutateType(NewTy);
  1646. }
  1647. /// \brief Mutate the instruction back to its original type.
  1648. void undo() override {
  1649. DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
  1650. << "\n");
  1651. Inst->mutateType(OrigTy);
  1652. }
  1653. };
  1654. /// \brief Replace the uses of an instruction by another instruction.
  1655. class UsesReplacer : public TypePromotionAction {
  1656. /// Helper structure to keep track of the replaced uses.
  1657. struct InstructionAndIdx {
  1658. /// The instruction using the instruction.
  1659. Instruction *Inst;
  1660. /// The index where this instruction is used for Inst.
  1661. unsigned Idx;
  1662. InstructionAndIdx(Instruction *Inst, unsigned Idx)
  1663. : Inst(Inst), Idx(Idx) {}
  1664. };
  1665. /// Keep track of the original uses (pair Instruction, Index).
  1666. SmallVector<InstructionAndIdx, 4> OriginalUses;
  1667. typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
  1668. public:
  1669. /// \brief Replace all the use of \p Inst by \p New.
  1670. UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
  1671. DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
  1672. << "\n");
  1673. // Record the original uses.
  1674. for (Use &U : Inst->uses()) {
  1675. Instruction *UserI = cast<Instruction>(U.getUser());
  1676. OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
  1677. }
  1678. // Now, we can replace the uses.
  1679. Inst->replaceAllUsesWith(New);
  1680. }
  1681. /// \brief Reassign the original uses of Inst to Inst.
  1682. void undo() override {
  1683. DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
  1684. for (use_iterator UseIt = OriginalUses.begin(),
  1685. EndIt = OriginalUses.end();
  1686. UseIt != EndIt; ++UseIt) {
  1687. UseIt->Inst->setOperand(UseIt->Idx, Inst);
  1688. }
  1689. }
  1690. };
  1691. /// \brief Remove an instruction from the IR.
  1692. class InstructionRemover : public TypePromotionAction {
  1693. /// Original position of the instruction.
  1694. InsertionHandler Inserter;
  1695. /// Helper structure to hide all the link to the instruction. In other
  1696. /// words, this helps to do as if the instruction was removed.
  1697. OperandsHider Hider;
  1698. /// Keep track of the uses replaced, if any.
  1699. UsesReplacer *Replacer;
  1700. public:
  1701. /// \brief Remove all reference of \p Inst and optinally replace all its
  1702. /// uses with New.
  1703. /// \pre If !Inst->use_empty(), then New != nullptr
  1704. InstructionRemover(Instruction *Inst, Value *New = nullptr)
  1705. : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
  1706. Replacer(nullptr) {
  1707. if (New)
  1708. Replacer = new UsesReplacer(Inst, New);
  1709. DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
  1710. Inst->removeFromParent();
  1711. }
  1712. ~InstructionRemover() override { delete Replacer; }
  1713. /// \brief Really remove the instruction.
  1714. void commit() override { delete Inst; }
  1715. /// \brief Resurrect the instruction and reassign it to the proper uses if
  1716. /// new value was provided when build this action.
  1717. void undo() override {
  1718. DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
  1719. Inserter.insert(Inst);
  1720. if (Replacer)
  1721. Replacer->undo();
  1722. Hider.undo();
  1723. }
  1724. };
  1725. public:
  1726. /// Restoration point.
  1727. /// The restoration point is a pointer to an action instead of an iterator
  1728. /// because the iterator may be invalidated but not the pointer.
  1729. typedef const TypePromotionAction *ConstRestorationPt;
  1730. /// Advocate every changes made in that transaction.
  1731. void commit();
  1732. /// Undo all the changes made after the given point.
  1733. void rollback(ConstRestorationPt Point);
  1734. /// Get the current restoration point.
  1735. ConstRestorationPt getRestorationPoint() const;
  1736. /// \name API for IR modification with state keeping to support rollback.
  1737. /// @{
  1738. /// Same as Instruction::setOperand.
  1739. void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
  1740. /// Same as Instruction::eraseFromParent.
  1741. void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
  1742. /// Same as Value::replaceAllUsesWith.
  1743. void replaceAllUsesWith(Instruction *Inst, Value *New);
  1744. /// Same as Value::mutateType.
  1745. void mutateType(Instruction *Inst, Type *NewTy);
  1746. /// Same as IRBuilder::createTrunc.
  1747. Value *createTrunc(Instruction *Opnd, Type *Ty);
  1748. /// Same as IRBuilder::createSExt.
  1749. Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
  1750. /// Same as IRBuilder::createZExt.
  1751. Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
  1752. /// Same as Instruction::moveBefore.
  1753. void moveBefore(Instruction *Inst, Instruction *Before);
  1754. /// @}
  1755. private:
  1756. /// The ordered list of actions made so far.
  1757. SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
  1758. typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
  1759. };
  1760. void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
  1761. Value *NewVal) {
  1762. Actions.push_back(
  1763. make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
  1764. }
  1765. void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
  1766. Value *NewVal) {
  1767. Actions.push_back(
  1768. make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
  1769. }
  1770. void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
  1771. Value *New) {
  1772. Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
  1773. }
  1774. void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
  1775. Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
  1776. }
  1777. Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
  1778. Type *Ty) {
  1779. std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
  1780. Value *Val = Ptr->getBuiltValue();
  1781. Actions.push_back(std::move(Ptr));
  1782. return Val;
  1783. }
  1784. Value *TypePromotionTransaction::createSExt(Instruction *Inst,
  1785. Value *Opnd, Type *Ty) {
  1786. std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
  1787. Value *Val = Ptr->getBuiltValue();
  1788. Actions.push_back(std::move(Ptr));
  1789. return Val;
  1790. }
  1791. Value *TypePromotionTransaction::createZExt(Instruction *Inst,
  1792. Value *Opnd, Type *Ty) {
  1793. std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
  1794. Value *Val = Ptr->getBuiltValue();
  1795. Actions.push_back(std::move(Ptr));
  1796. return Val;
  1797. }
  1798. void TypePromotionTransaction::moveBefore(Instruction *Inst,
  1799. Instruction *Before) {
  1800. Actions.push_back(
  1801. make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
  1802. }
  1803. TypePromotionTransaction::ConstRestorationPt
  1804. TypePromotionTransaction::getRestorationPoint() const {
  1805. return !Actions.empty() ? Actions.back().get() : nullptr;
  1806. }
  1807. void TypePromotionTransaction::commit() {
  1808. for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
  1809. ++It)
  1810. (*It)->commit();
  1811. Actions.clear();
  1812. }
  1813. void TypePromotionTransaction::rollback(
  1814. TypePromotionTransaction::ConstRestorationPt Point) {
  1815. while (!Actions.empty() && Point != Actions.back().get()) {
  1816. std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
  1817. Curr->undo();
  1818. }
  1819. }
  1820. /// \brief A helper class for matching addressing modes.
  1821. ///
  1822. /// This encapsulates the logic for matching the target-legal addressing modes.
  1823. class AddressingModeMatcher {
  1824. SmallVectorImpl<Instruction*> &AddrModeInsts;
  1825. const TargetMachine &TM;
  1826. const TargetLowering &TLI;
  1827. const DataLayout &DL;
  1828. /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
  1829. /// the memory instruction that we're computing this address for.
  1830. Type *AccessTy;
  1831. unsigned AddrSpace;
  1832. Instruction *MemoryInst;
  1833. /// AddrMode - This is the addressing mode that we're building up. This is
  1834. /// part of the return value of this addressing mode matching stuff.
  1835. ExtAddrMode &AddrMode;
  1836. /// The instructions inserted by other CodeGenPrepare optimizations.
  1837. const SetOfInstrs &InsertedInsts;
  1838. /// A map from the instructions to their type before promotion.
  1839. InstrToOrigTy &PromotedInsts;
  1840. /// The ongoing transaction where every action should be registered.
  1841. TypePromotionTransaction &TPT;
  1842. /// IgnoreProfitability - This is set to true when we should not do
  1843. /// profitability checks. When true, IsProfitableToFoldIntoAddressingMode
  1844. /// always returns true.
  1845. bool IgnoreProfitability;
  1846. AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
  1847. const TargetMachine &TM, Type *AT, unsigned AS,
  1848. Instruction *MI, ExtAddrMode &AM,
  1849. const SetOfInstrs &InsertedInsts,
  1850. InstrToOrigTy &PromotedInsts,
  1851. TypePromotionTransaction &TPT)
  1852. : AddrModeInsts(AMI), TM(TM),
  1853. TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
  1854. ->getTargetLowering()),
  1855. DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
  1856. MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
  1857. PromotedInsts(PromotedInsts), TPT(TPT) {
  1858. IgnoreProfitability = false;
  1859. }
  1860. public:
  1861. /// Match - Find the maximal addressing mode that a load/store of V can fold,
  1862. /// give an access type of AccessTy. This returns a list of involved
  1863. /// instructions in AddrModeInsts.
  1864. /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
  1865. /// optimizations.
  1866. /// \p PromotedInsts maps the instructions to their type before promotion.
  1867. /// \p The ongoing transaction where every action should be registered.
  1868. static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
  1869. Instruction *MemoryInst,
  1870. SmallVectorImpl<Instruction*> &AddrModeInsts,
  1871. const TargetMachine &TM,
  1872. const SetOfInstrs &InsertedInsts,
  1873. InstrToOrigTy &PromotedInsts,
  1874. TypePromotionTransaction &TPT) {
  1875. ExtAddrMode Result;
  1876. bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
  1877. MemoryInst, Result, InsertedInsts,
  1878. PromotedInsts, TPT).MatchAddr(V, 0);
  1879. (void)Success; assert(Success && "Couldn't select *anything*?");
  1880. return Result;
  1881. }
  1882. private:
  1883. bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
  1884. bool MatchAddr(Value *V, unsigned Depth);
  1885. bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
  1886. bool *MovedAway = nullptr);
  1887. bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
  1888. ExtAddrMode &AMBefore,
  1889. ExtAddrMode &AMAfter);
  1890. bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
  1891. bool IsPromotionProfitable(unsigned NewCost, unsigned OldCost,
  1892. Value *PromotedOperand) const;
  1893. };
  1894. /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
  1895. /// Return true and update AddrMode if this addr mode is legal for the target,
  1896. /// false if not.
  1897. bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
  1898. unsigned Depth) {
  1899. // If Scale is 1, then this is the same as adding ScaleReg to the addressing
  1900. // mode. Just process that directly.
  1901. if (Scale == 1)
  1902. return MatchAddr(ScaleReg, Depth);
  1903. // If the scale is 0, it takes nothing to add this.
  1904. if (Scale == 0)
  1905. return true;
  1906. // If we already have a scale of this value, we can add to it, otherwise, we
  1907. // need an available scale field.
  1908. if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
  1909. return false;
  1910. ExtAddrMode TestAddrMode = AddrMode;
  1911. // Add scale to turn X*4+X*3 -> X*7. This could also do things like
  1912. // [A+B + A*7] -> [B+A*8].
  1913. TestAddrMode.Scale += Scale;
  1914. TestAddrMode.ScaledReg = ScaleReg;
  1915. // If the new address isn't legal, bail out.
  1916. if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
  1917. return false;
  1918. // It was legal, so commit it.
  1919. AddrMode = TestAddrMode;
  1920. // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
  1921. // to see if ScaleReg is actually X+C. If so, we can turn this into adding
  1922. // X*Scale + C*Scale to addr mode.
  1923. ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
  1924. if (isa<Instruction>(ScaleReg) && // not a constant expr.
  1925. match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
  1926. TestAddrMode.ScaledReg = AddLHS;
  1927. TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
  1928. // If this addressing mode is legal, commit it and remember that we folded
  1929. // this instruction.
  1930. if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
  1931. AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
  1932. AddrMode = TestAddrMode;
  1933. return true;
  1934. }
  1935. }
  1936. // Otherwise, not (x+c)*scale, just return what we have.
  1937. return true;
  1938. }
  1939. /// MightBeFoldableInst - This is a little filter, which returns true if an
  1940. /// addressing computation involving I might be folded into a load/store
  1941. /// accessing it. This doesn't need to be perfect, but needs to accept at least
  1942. /// the set of instructions that MatchOperationAddr can.
  1943. static bool MightBeFoldableInst(Instruction *I) {
  1944. switch (I->getOpcode()) {
  1945. case Instruction::BitCast:
  1946. case Instruction::AddrSpaceCast:
  1947. // Don't touch identity bitcasts.
  1948. if (I->getType() == I->getOperand(0)->getType())
  1949. return false;
  1950. return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
  1951. case Instruction::PtrToInt:
  1952. // PtrToInt is always a noop, as we know that the int type is pointer sized.
  1953. return true;
  1954. case Instruction::IntToPtr:
  1955. // We know the input is intptr_t, so this is foldable.
  1956. return true;
  1957. case Instruction::Add:
  1958. return true;
  1959. case Instruction::Mul:
  1960. case Instruction::Shl:
  1961. // Can only handle X*C and X << C.
  1962. return isa<ConstantInt>(I->getOperand(1));
  1963. case Instruction::GetElementPtr:
  1964. return true;
  1965. default:
  1966. return false;
  1967. }
  1968. }
  1969. /// \brief Check whether or not \p Val is a legal instruction for \p TLI.
  1970. /// \note \p Val is assumed to be the product of some type promotion.
  1971. /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
  1972. /// to be legal, as the non-promoted value would have had the same state.
  1973. static bool isPromotedInstructionLegal(const TargetLowering &TLI,
  1974. const DataLayout &DL, Value *Val) {
  1975. Instruction *PromotedInst = dyn_cast<Instruction>(Val);
  1976. if (!PromotedInst)
  1977. return false;
  1978. int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
  1979. // If the ISDOpcode is undefined, it was undefined before the promotion.
  1980. if (!ISDOpcode)
  1981. return true;
  1982. // Otherwise, check if the promoted instruction is legal or not.
  1983. return TLI.isOperationLegalOrCustom(
  1984. ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
  1985. }
  1986. /// \brief Hepler class to perform type promotion.
  1987. class TypePromotionHelper {
  1988. /// \brief Utility function to check whether or not a sign or zero extension
  1989. /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
  1990. /// either using the operands of \p Inst or promoting \p Inst.
  1991. /// The type of the extension is defined by \p IsSExt.
  1992. /// In other words, check if:
  1993. /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
  1994. /// #1 Promotion applies:
  1995. /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
  1996. /// #2 Operand reuses:
  1997. /// ext opnd1 to ConsideredExtType.
  1998. /// \p PromotedInsts maps the instructions to their type before promotion.
  1999. static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
  2000. const InstrToOrigTy &PromotedInsts, bool IsSExt);
  2001. /// \brief Utility function to determine if \p OpIdx should be promoted when
  2002. /// promoting \p Inst.
  2003. static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
  2004. if (isa<SelectInst>(Inst) && OpIdx == 0)
  2005. return false;
  2006. return true;
  2007. }
  2008. /// \brief Utility function to promote the operand of \p Ext when this
  2009. /// operand is a promotable trunc or sext or zext.
  2010. /// \p PromotedInsts maps the instructions to their type before promotion.
  2011. /// \p CreatedInstsCost[out] contains the cost of all instructions
  2012. /// created to promote the operand of Ext.
  2013. /// Newly added extensions are inserted in \p Exts.
  2014. /// Newly added truncates are inserted in \p Truncs.
  2015. /// Should never be called directly.
  2016. /// \return The promoted value which is used instead of Ext.
  2017. static Value *promoteOperandForTruncAndAnyExt(
  2018. Instruction *Ext, TypePromotionTransaction &TPT,
  2019. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  2020. SmallVectorImpl<Instruction *> *Exts,
  2021. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
  2022. /// \brief Utility function to promote the operand of \p Ext when this
  2023. /// operand is promotable and is not a supported trunc or sext.
  2024. /// \p PromotedInsts maps the instructions to their type before promotion.
  2025. /// \p CreatedInstsCost[out] contains the cost of all the instructions
  2026. /// created to promote the operand of Ext.
  2027. /// Newly added extensions are inserted in \p Exts.
  2028. /// Newly added truncates are inserted in \p Truncs.
  2029. /// Should never be called directly.
  2030. /// \return The promoted value which is used instead of Ext.
  2031. static Value *promoteOperandForOther(Instruction *Ext,
  2032. TypePromotionTransaction &TPT,
  2033. InstrToOrigTy &PromotedInsts,
  2034. unsigned &CreatedInstsCost,
  2035. SmallVectorImpl<Instruction *> *Exts,
  2036. SmallVectorImpl<Instruction *> *Truncs,
  2037. const TargetLowering &TLI, bool IsSExt);
  2038. /// \see promoteOperandForOther.
  2039. static Value *signExtendOperandForOther(
  2040. Instruction *Ext, TypePromotionTransaction &TPT,
  2041. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  2042. SmallVectorImpl<Instruction *> *Exts,
  2043. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  2044. return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
  2045. Exts, Truncs, TLI, true);
  2046. }
  2047. /// \see promoteOperandForOther.
  2048. static Value *zeroExtendOperandForOther(
  2049. Instruction *Ext, TypePromotionTransaction &TPT,
  2050. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  2051. SmallVectorImpl<Instruction *> *Exts,
  2052. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  2053. return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
  2054. Exts, Truncs, TLI, false);
  2055. }
  2056. public:
  2057. /// Type for the utility function that promotes the operand of Ext.
  2058. typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
  2059. InstrToOrigTy &PromotedInsts,
  2060. unsigned &CreatedInstsCost,
  2061. SmallVectorImpl<Instruction *> *Exts,
  2062. SmallVectorImpl<Instruction *> *Truncs,
  2063. const TargetLowering &TLI);
  2064. /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
  2065. /// action to promote the operand of \p Ext instead of using Ext.
  2066. /// \return NULL if no promotable action is possible with the current
  2067. /// sign extension.
  2068. /// \p InsertedInsts keeps track of all the instructions inserted by the
  2069. /// other CodeGenPrepare optimizations. This information is important
  2070. /// because we do not want to promote these instructions as CodeGenPrepare
  2071. /// will reinsert them later. Thus creating an infinite loop: create/remove.
  2072. /// \p PromotedInsts maps the instructions to their type before promotion.
  2073. static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
  2074. const TargetLowering &TLI,
  2075. const InstrToOrigTy &PromotedInsts);
  2076. };
  2077. bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
  2078. Type *ConsideredExtType,
  2079. const InstrToOrigTy &PromotedInsts,
  2080. bool IsSExt) {
  2081. // The promotion helper does not know how to deal with vector types yet.
  2082. // To be able to fix that, we would need to fix the places where we
  2083. // statically extend, e.g., constants and such.
  2084. if (Inst->getType()->isVectorTy())
  2085. return false;
  2086. // We can always get through zext.
  2087. if (isa<ZExtInst>(Inst))
  2088. return true;
  2089. // sext(sext) is ok too.
  2090. if (IsSExt && isa<SExtInst>(Inst))
  2091. return true;
  2092. // We can get through binary operator, if it is legal. In other words, the
  2093. // binary operator must have a nuw or nsw flag.
  2094. const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
  2095. if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
  2096. ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
  2097. (IsSExt && BinOp->hasNoSignedWrap())))
  2098. return true;
  2099. // Check if we can do the following simplification.
  2100. // ext(trunc(opnd)) --> ext(opnd)
  2101. if (!isa<TruncInst>(Inst))
  2102. return false;
  2103. Value *OpndVal = Inst->getOperand(0);
  2104. // Check if we can use this operand in the extension.
  2105. // If the type is larger than the result type of the extension,
  2106. // we cannot.
  2107. if (!OpndVal->getType()->isIntegerTy() ||
  2108. OpndVal->getType()->getIntegerBitWidth() >
  2109. ConsideredExtType->getIntegerBitWidth())
  2110. return false;
  2111. // If the operand of the truncate is not an instruction, we will not have
  2112. // any information on the dropped bits.
  2113. // (Actually we could for constant but it is not worth the extra logic).
  2114. Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
  2115. if (!Opnd)
  2116. return false;
  2117. // Check if the source of the type is narrow enough.
  2118. // I.e., check that trunc just drops extended bits of the same kind of
  2119. // the extension.
  2120. // #1 get the type of the operand and check the kind of the extended bits.
  2121. const Type *OpndType;
  2122. InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
  2123. if (It != PromotedInsts.end() && It->second.IsSExt == IsSExt)
  2124. OpndType = It->second.Ty;
  2125. else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
  2126. OpndType = Opnd->getOperand(0)->getType();
  2127. else
  2128. return false;
  2129. // #2 check that the truncate just drop extended bits.
  2130. if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
  2131. return true;
  2132. return false;
  2133. }
  2134. TypePromotionHelper::Action TypePromotionHelper::getAction(
  2135. Instruction *Ext, const SetOfInstrs &InsertedInsts,
  2136. const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
  2137. assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
  2138. "Unexpected instruction type");
  2139. Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
  2140. Type *ExtTy = Ext->getType();
  2141. bool IsSExt = isa<SExtInst>(Ext);
  2142. // If the operand of the extension is not an instruction, we cannot
  2143. // get through.
  2144. // If it, check we can get through.
  2145. if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
  2146. return nullptr;
  2147. // Do not promote if the operand has been added by codegenprepare.
  2148. // Otherwise, it means we are undoing an optimization that is likely to be
  2149. // redone, thus causing potential infinite loop.
  2150. if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
  2151. return nullptr;
  2152. // SExt or Trunc instructions.
  2153. // Return the related handler.
  2154. if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
  2155. isa<ZExtInst>(ExtOpnd))
  2156. return promoteOperandForTruncAndAnyExt;
  2157. // Regular instruction.
  2158. // Abort early if we will have to insert non-free instructions.
  2159. if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
  2160. return nullptr;
  2161. return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
  2162. }
  2163. Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
  2164. llvm::Instruction *SExt, TypePromotionTransaction &TPT,
  2165. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  2166. SmallVectorImpl<Instruction *> *Exts,
  2167. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  2168. // By construction, the operand of SExt is an instruction. Otherwise we cannot
  2169. // get through it and this method should not be called.
  2170. Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
  2171. Value *ExtVal = SExt;
  2172. bool HasMergedNonFreeExt = false;
  2173. if (isa<ZExtInst>(SExtOpnd)) {
  2174. // Replace s|zext(zext(opnd))
  2175. // => zext(opnd).
  2176. HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
  2177. Value *ZExt =
  2178. TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
  2179. TPT.replaceAllUsesWith(SExt, ZExt);
  2180. TPT.eraseInstruction(SExt);
  2181. ExtVal = ZExt;
  2182. } else {
  2183. // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
  2184. // => z|sext(opnd).
  2185. TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
  2186. }
  2187. CreatedInstsCost = 0;
  2188. // Remove dead code.
  2189. if (SExtOpnd->use_empty())
  2190. TPT.eraseInstruction(SExtOpnd);
  2191. // Check if the extension is still needed.
  2192. Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
  2193. if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
  2194. if (ExtInst) {
  2195. if (Exts)
  2196. Exts->push_back(ExtInst);
  2197. CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
  2198. }
  2199. return ExtVal;
  2200. }
  2201. // At this point we have: ext ty opnd to ty.
  2202. // Reassign the uses of ExtInst to the opnd and remove ExtInst.
  2203. Value *NextVal = ExtInst->getOperand(0);
  2204. TPT.eraseInstruction(ExtInst, NextVal);
  2205. return NextVal;
  2206. }
  2207. Value *TypePromotionHelper::promoteOperandForOther(
  2208. Instruction *Ext, TypePromotionTransaction &TPT,
  2209. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  2210. SmallVectorImpl<Instruction *> *Exts,
  2211. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
  2212. bool IsSExt) {
  2213. // By construction, the operand of Ext is an instruction. Otherwise we cannot
  2214. // get through it and this method should not be called.
  2215. Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
  2216. CreatedInstsCost = 0;
  2217. if (!ExtOpnd->hasOneUse()) {
  2218. // ExtOpnd will be promoted.
  2219. // All its uses, but Ext, will need to use a truncated value of the
  2220. // promoted version.
  2221. // Create the truncate now.
  2222. Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
  2223. if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
  2224. ITrunc->removeFromParent();
  2225. // Insert it just after the definition.
  2226. ITrunc->insertAfter(ExtOpnd);
  2227. if (Truncs)
  2228. Truncs->push_back(ITrunc);
  2229. }
  2230. TPT.replaceAllUsesWith(ExtOpnd, Trunc);
  2231. // Restore the operand of Ext (which has been replace by the previous call
  2232. // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
  2233. TPT.setOperand(Ext, 0, ExtOpnd);
  2234. }
  2235. // Get through the Instruction:
  2236. // 1. Update its type.
  2237. // 2. Replace the uses of Ext by Inst.
  2238. // 3. Extend each operand that needs to be extended.
  2239. // Remember the original type of the instruction before promotion.
  2240. // This is useful to know that the high bits are sign extended bits.
  2241. PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
  2242. ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
  2243. // Step #1.
  2244. TPT.mutateType(ExtOpnd, Ext->getType());
  2245. // Step #2.
  2246. TPT.replaceAllUsesWith(Ext, ExtOpnd);
  2247. // Step #3.
  2248. Instruction *ExtForOpnd = Ext;
  2249. DEBUG(dbgs() << "Propagate Ext to operands\n");
  2250. for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
  2251. ++OpIdx) {
  2252. DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
  2253. if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
  2254. !shouldExtOperand(ExtOpnd, OpIdx)) {
  2255. DEBUG(dbgs() << "No need to propagate\n");
  2256. continue;
  2257. }
  2258. // Check if we can statically extend the operand.
  2259. Value *Opnd = ExtOpnd->getOperand(OpIdx);
  2260. if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
  2261. DEBUG(dbgs() << "Statically extend\n");
  2262. unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
  2263. APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
  2264. : Cst->getValue().zext(BitWidth);
  2265. TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
  2266. continue;
  2267. }
  2268. // UndefValue are typed, so we have to statically sign extend them.
  2269. if (isa<UndefValue>(Opnd)) {
  2270. DEBUG(dbgs() << "Statically extend\n");
  2271. TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
  2272. continue;
  2273. }
  2274. // Otherwise we have to explicity sign extend the operand.
  2275. // Check if Ext was reused to extend an operand.
  2276. if (!ExtForOpnd) {
  2277. // If yes, create a new one.
  2278. DEBUG(dbgs() << "More operands to ext\n");
  2279. Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
  2280. : TPT.createZExt(Ext, Opnd, Ext->getType());
  2281. if (!isa<Instruction>(ValForExtOpnd)) {
  2282. TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
  2283. continue;
  2284. }
  2285. ExtForOpnd = cast<Instruction>(ValForExtOpnd);
  2286. }
  2287. if (Exts)
  2288. Exts->push_back(ExtForOpnd);
  2289. TPT.setOperand(ExtForOpnd, 0, Opnd);
  2290. // Move the sign extension before the insertion point.
  2291. TPT.moveBefore(ExtForOpnd, ExtOpnd);
  2292. TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
  2293. CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
  2294. // If more sext are required, new instructions will have to be created.
  2295. ExtForOpnd = nullptr;
  2296. }
  2297. if (ExtForOpnd == Ext) {
  2298. DEBUG(dbgs() << "Extension is useless now\n");
  2299. TPT.eraseInstruction(Ext);
  2300. }
  2301. return ExtOpnd;
  2302. }
  2303. /// IsPromotionProfitable - Check whether or not promoting an instruction
  2304. /// to a wider type was profitable.
  2305. /// \p NewCost gives the cost of extension instructions created by the
  2306. /// promotion.
  2307. /// \p OldCost gives the cost of extension instructions before the promotion
  2308. /// plus the number of instructions that have been
  2309. /// matched in the addressing mode the promotion.
  2310. /// \p PromotedOperand is the value that has been promoted.
  2311. /// \return True if the promotion is profitable, false otherwise.
  2312. bool AddressingModeMatcher::IsPromotionProfitable(
  2313. unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
  2314. DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
  2315. // The cost of the new extensions is greater than the cost of the
  2316. // old extension plus what we folded.
  2317. // This is not profitable.
  2318. if (NewCost > OldCost)
  2319. return false;
  2320. if (NewCost < OldCost)
  2321. return true;
  2322. // The promotion is neutral but it may help folding the sign extension in
  2323. // loads for instance.
  2324. // Check that we did not create an illegal instruction.
  2325. return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
  2326. }
  2327. /// MatchOperationAddr - Given an instruction or constant expr, see if we can
  2328. /// fold the operation into the addressing mode. If so, update the addressing
  2329. /// mode and return true, otherwise return false without modifying AddrMode.
  2330. /// If \p MovedAway is not NULL, it contains the information of whether or
  2331. /// not AddrInst has to be folded into the addressing mode on success.
  2332. /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
  2333. /// because it has been moved away.
  2334. /// Thus AddrInst must not be added in the matched instructions.
  2335. /// This state can happen when AddrInst is a sext, since it may be moved away.
  2336. /// Therefore, AddrInst may not be valid when MovedAway is true and it must
  2337. /// not be referenced anymore.
  2338. bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
  2339. unsigned Depth,
  2340. bool *MovedAway) {
  2341. // Avoid exponential behavior on extremely deep expression trees.
  2342. if (Depth >= 5) return false;
  2343. // By default, all matched instructions stay in place.
  2344. if (MovedAway)
  2345. *MovedAway = false;
  2346. switch (Opcode) {
  2347. case Instruction::PtrToInt:
  2348. // PtrToInt is always a noop, as we know that the int type is pointer sized.
  2349. return MatchAddr(AddrInst->getOperand(0), Depth);
  2350. case Instruction::IntToPtr: {
  2351. auto AS = AddrInst->getType()->getPointerAddressSpace();
  2352. auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
  2353. // This inttoptr is a no-op if the integer type is pointer sized.
  2354. if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
  2355. return MatchAddr(AddrInst->getOperand(0), Depth);
  2356. return false;
  2357. }
  2358. case Instruction::BitCast:
  2359. // BitCast is always a noop, and we can handle it as long as it is
  2360. // int->int or pointer->pointer (we don't want int<->fp or something).
  2361. if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
  2362. AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
  2363. // Don't touch identity bitcasts. These were probably put here by LSR,
  2364. // and we don't want to mess around with them. Assume it knows what it
  2365. // is doing.
  2366. AddrInst->getOperand(0)->getType() != AddrInst->getType())
  2367. return MatchAddr(AddrInst->getOperand(0), Depth);
  2368. return false;
  2369. case Instruction::AddrSpaceCast: {
  2370. unsigned SrcAS
  2371. = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
  2372. unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
  2373. if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  2374. return MatchAddr(AddrInst->getOperand(0), Depth);
  2375. return false;
  2376. }
  2377. case Instruction::Add: {
  2378. // Check to see if we can merge in the RHS then the LHS. If so, we win.
  2379. ExtAddrMode BackupAddrMode = AddrMode;
  2380. unsigned OldSize = AddrModeInsts.size();
  2381. // Start a transaction at this point.
  2382. // The LHS may match but not the RHS.
  2383. // Therefore, we need a higher level restoration point to undo partially
  2384. // matched operation.
  2385. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  2386. TPT.getRestorationPoint();
  2387. if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
  2388. MatchAddr(AddrInst->getOperand(0), Depth+1))
  2389. return true;
  2390. // Restore the old addr mode info.
  2391. AddrMode = BackupAddrMode;
  2392. AddrModeInsts.resize(OldSize);
  2393. TPT.rollback(LastKnownGood);
  2394. // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
  2395. if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
  2396. MatchAddr(AddrInst->getOperand(1), Depth+1))
  2397. return true;
  2398. // Otherwise we definitely can't merge the ADD in.
  2399. AddrMode = BackupAddrMode;
  2400. AddrModeInsts.resize(OldSize);
  2401. TPT.rollback(LastKnownGood);
  2402. break;
  2403. }
  2404. //case Instruction::Or:
  2405. // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
  2406. //break;
  2407. case Instruction::Mul:
  2408. case Instruction::Shl: {
  2409. // Can only handle X*C and X << C.
  2410. ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
  2411. if (!RHS)
  2412. return false;
  2413. int64_t Scale = RHS->getSExtValue();
  2414. if (Opcode == Instruction::Shl)
  2415. Scale = 1LL << Scale;
  2416. return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
  2417. }
  2418. case Instruction::GetElementPtr: {
  2419. // Scan the GEP. We check it if it contains constant offsets and at most
  2420. // one variable offset.
  2421. int VariableOperand = -1;
  2422. unsigned VariableScale = 0;
  2423. int64_t ConstantOffset = 0;
  2424. gep_type_iterator GTI = gep_type_begin(AddrInst);
  2425. for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
  2426. if (StructType *STy = dyn_cast<StructType>(*GTI)) {
  2427. const StructLayout *SL = DL.getStructLayout(STy);
  2428. unsigned Idx =
  2429. cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
  2430. ConstantOffset += SL->getElementOffset(Idx);
  2431. } else {
  2432. uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
  2433. if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
  2434. ConstantOffset += CI->getSExtValue()*TypeSize;
  2435. } else if (TypeSize) { // Scales of zero don't do anything.
  2436. // We only allow one variable index at the moment.
  2437. if (VariableOperand != -1)
  2438. return false;
  2439. // Remember the variable index.
  2440. VariableOperand = i;
  2441. VariableScale = TypeSize;
  2442. }
  2443. }
  2444. }
  2445. // A common case is for the GEP to only do a constant offset. In this case,
  2446. // just add it to the disp field and check validity.
  2447. if (VariableOperand == -1) {
  2448. AddrMode.BaseOffs += ConstantOffset;
  2449. if (ConstantOffset == 0 ||
  2450. TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
  2451. // Check to see if we can fold the base pointer in too.
  2452. if (MatchAddr(AddrInst->getOperand(0), Depth+1))
  2453. return true;
  2454. }
  2455. AddrMode.BaseOffs -= ConstantOffset;
  2456. return false;
  2457. }
  2458. // Save the valid addressing mode in case we can't match.
  2459. ExtAddrMode BackupAddrMode = AddrMode;
  2460. unsigned OldSize = AddrModeInsts.size();
  2461. // See if the scale and offset amount is valid for this target.
  2462. AddrMode.BaseOffs += ConstantOffset;
  2463. // Match the base operand of the GEP.
  2464. if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
  2465. // If it couldn't be matched, just stuff the value in a register.
  2466. if (AddrMode.HasBaseReg) {
  2467. AddrMode = BackupAddrMode;
  2468. AddrModeInsts.resize(OldSize);
  2469. return false;
  2470. }
  2471. AddrMode.HasBaseReg = true;
  2472. AddrMode.BaseReg = AddrInst->getOperand(0);
  2473. }
  2474. // Match the remaining variable portion of the GEP.
  2475. if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
  2476. Depth)) {
  2477. // If it couldn't be matched, try stuffing the base into a register
  2478. // instead of matching it, and retrying the match of the scale.
  2479. AddrMode = BackupAddrMode;
  2480. AddrModeInsts.resize(OldSize);
  2481. if (AddrMode.HasBaseReg)
  2482. return false;
  2483. AddrMode.HasBaseReg = true;
  2484. AddrMode.BaseReg = AddrInst->getOperand(0);
  2485. AddrMode.BaseOffs += ConstantOffset;
  2486. if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
  2487. VariableScale, Depth)) {
  2488. // If even that didn't work, bail.
  2489. AddrMode = BackupAddrMode;
  2490. AddrModeInsts.resize(OldSize);
  2491. return false;
  2492. }
  2493. }
  2494. return true;
  2495. }
  2496. case Instruction::SExt:
  2497. case Instruction::ZExt: {
  2498. Instruction *Ext = dyn_cast<Instruction>(AddrInst);
  2499. if (!Ext)
  2500. return false;
  2501. // Try to move this ext out of the way of the addressing mode.
  2502. // Ask for a method for doing so.
  2503. TypePromotionHelper::Action TPH =
  2504. TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
  2505. if (!TPH)
  2506. return false;
  2507. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  2508. TPT.getRestorationPoint();
  2509. unsigned CreatedInstsCost = 0;
  2510. unsigned ExtCost = !TLI.isExtFree(Ext);
  2511. Value *PromotedOperand =
  2512. TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
  2513. // SExt has been moved away.
  2514. // Thus either it will be rematched later in the recursive calls or it is
  2515. // gone. Anyway, we must not fold it into the addressing mode at this point.
  2516. // E.g.,
  2517. // op = add opnd, 1
  2518. // idx = ext op
  2519. // addr = gep base, idx
  2520. // is now:
  2521. // promotedOpnd = ext opnd <- no match here
  2522. // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
  2523. // addr = gep base, op <- match
  2524. if (MovedAway)
  2525. *MovedAway = true;
  2526. assert(PromotedOperand &&
  2527. "TypePromotionHelper should have filtered out those cases");
  2528. ExtAddrMode BackupAddrMode = AddrMode;
  2529. unsigned OldSize = AddrModeInsts.size();
  2530. if (!MatchAddr(PromotedOperand, Depth) ||
  2531. // The total of the new cost is equals to the cost of the created
  2532. // instructions.
  2533. // The total of the old cost is equals to the cost of the extension plus
  2534. // what we have saved in the addressing mode.
  2535. !IsPromotionProfitable(CreatedInstsCost,
  2536. ExtCost + (AddrModeInsts.size() - OldSize),
  2537. PromotedOperand)) {
  2538. AddrMode = BackupAddrMode;
  2539. AddrModeInsts.resize(OldSize);
  2540. DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
  2541. TPT.rollback(LastKnownGood);
  2542. return false;
  2543. }
  2544. return true;
  2545. }
  2546. }
  2547. return false;
  2548. }
  2549. /// MatchAddr - If we can, try to add the value of 'Addr' into the current
  2550. /// addressing mode. If Addr can't be added to AddrMode this returns false and
  2551. /// leaves AddrMode unmodified. This assumes that Addr is either a pointer type
  2552. /// or intptr_t for the target.
  2553. ///
  2554. bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
  2555. // Start a transaction at this point that we will rollback if the matching
  2556. // fails.
  2557. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  2558. TPT.getRestorationPoint();
  2559. if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
  2560. // Fold in immediates if legal for the target.
  2561. AddrMode.BaseOffs += CI->getSExtValue();
  2562. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  2563. return true;
  2564. AddrMode.BaseOffs -= CI->getSExtValue();
  2565. } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
  2566. // If this is a global variable, try to fold it into the addressing mode.
  2567. if (!AddrMode.BaseGV) {
  2568. AddrMode.BaseGV = GV;
  2569. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  2570. return true;
  2571. AddrMode.BaseGV = nullptr;
  2572. }
  2573. } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
  2574. ExtAddrMode BackupAddrMode = AddrMode;
  2575. unsigned OldSize = AddrModeInsts.size();
  2576. // Check to see if it is possible to fold this operation.
  2577. bool MovedAway = false;
  2578. if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
  2579. // This instruction may have been move away. If so, there is nothing
  2580. // to check here.
  2581. if (MovedAway)
  2582. return true;
  2583. // Okay, it's possible to fold this. Check to see if it is actually
  2584. // *profitable* to do so. We use a simple cost model to avoid increasing
  2585. // register pressure too much.
  2586. if (I->hasOneUse() ||
  2587. IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
  2588. AddrModeInsts.push_back(I);
  2589. return true;
  2590. }
  2591. // It isn't profitable to do this, roll back.
  2592. //cerr << "NOT FOLDING: " << *I;
  2593. AddrMode = BackupAddrMode;
  2594. AddrModeInsts.resize(OldSize);
  2595. TPT.rollback(LastKnownGood);
  2596. }
  2597. } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
  2598. if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
  2599. return true;
  2600. TPT.rollback(LastKnownGood);
  2601. } else if (isa<ConstantPointerNull>(Addr)) {
  2602. // Null pointer gets folded without affecting the addressing mode.
  2603. return true;
  2604. }
  2605. // Worse case, the target should support [reg] addressing modes. :)
  2606. if (!AddrMode.HasBaseReg) {
  2607. AddrMode.HasBaseReg = true;
  2608. AddrMode.BaseReg = Addr;
  2609. // Still check for legality in case the target supports [imm] but not [i+r].
  2610. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  2611. return true;
  2612. AddrMode.HasBaseReg = false;
  2613. AddrMode.BaseReg = nullptr;
  2614. }
  2615. // If the base register is already taken, see if we can do [r+r].
  2616. if (AddrMode.Scale == 0) {
  2617. AddrMode.Scale = 1;
  2618. AddrMode.ScaledReg = Addr;
  2619. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  2620. return true;
  2621. AddrMode.Scale = 0;
  2622. AddrMode.ScaledReg = nullptr;
  2623. }
  2624. // Couldn't match.
  2625. TPT.rollback(LastKnownGood);
  2626. return false;
  2627. }
  2628. /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
  2629. /// inline asm call are due to memory operands. If so, return true, otherwise
  2630. /// return false.
  2631. static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
  2632. const TargetMachine &TM) {
  2633. const Function *F = CI->getParent()->getParent();
  2634. const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
  2635. const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
  2636. TargetLowering::AsmOperandInfoVector TargetConstraints =
  2637. TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
  2638. ImmutableCallSite(CI));
  2639. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  2640. TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
  2641. // Compute the constraint code and ConstraintType to use.
  2642. TLI->ComputeConstraintToUse(OpInfo, SDValue());
  2643. // If this asm operand is our Value*, and if it isn't an indirect memory
  2644. // operand, we can't fold it!
  2645. if (OpInfo.CallOperandVal == OpVal &&
  2646. (OpInfo.ConstraintType != TargetLowering::C_Memory ||
  2647. !OpInfo.isIndirect))
  2648. return false;
  2649. }
  2650. return true;
  2651. }
  2652. /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
  2653. /// memory use. If we find an obviously non-foldable instruction, return true.
  2654. /// Add the ultimately found memory instructions to MemoryUses.
  2655. static bool FindAllMemoryUses(
  2656. Instruction *I,
  2657. SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
  2658. SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
  2659. // If we already considered this instruction, we're done.
  2660. if (!ConsideredInsts.insert(I).second)
  2661. return false;
  2662. // If this is an obviously unfoldable instruction, bail out.
  2663. if (!MightBeFoldableInst(I))
  2664. return true;
  2665. // Loop over all the uses, recursively processing them.
  2666. for (Use &U : I->uses()) {
  2667. Instruction *UserI = cast<Instruction>(U.getUser());
  2668. if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
  2669. MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
  2670. continue;
  2671. }
  2672. if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
  2673. unsigned opNo = U.getOperandNo();
  2674. if (opNo == 0) return true; // Storing addr, not into addr.
  2675. MemoryUses.push_back(std::make_pair(SI, opNo));
  2676. continue;
  2677. }
  2678. if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
  2679. InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
  2680. if (!IA) return true;
  2681. // If this is a memory operand, we're cool, otherwise bail out.
  2682. if (!IsOperandAMemoryOperand(CI, IA, I, TM))
  2683. return true;
  2684. continue;
  2685. }
  2686. if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
  2687. return true;
  2688. }
  2689. return false;
  2690. }
  2691. /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
  2692. /// the use site that we're folding it into. If so, there is no cost to
  2693. /// include it in the addressing mode. KnownLive1 and KnownLive2 are two values
  2694. /// that we know are live at the instruction already.
  2695. bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
  2696. Value *KnownLive2) {
  2697. // If Val is either of the known-live values, we know it is live!
  2698. if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
  2699. return true;
  2700. // All values other than instructions and arguments (e.g. constants) are live.
  2701. if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
  2702. // If Val is a constant sized alloca in the entry block, it is live, this is
  2703. // true because it is just a reference to the stack/frame pointer, which is
  2704. // live for the whole function.
  2705. if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
  2706. if (AI->isStaticAlloca())
  2707. return true;
  2708. // Check to see if this value is already used in the memory instruction's
  2709. // block. If so, it's already live into the block at the very least, so we
  2710. // can reasonably fold it.
  2711. return Val->isUsedInBasicBlock(MemoryInst->getParent());
  2712. }
  2713. /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
  2714. /// mode of the machine to fold the specified instruction into a load or store
  2715. /// that ultimately uses it. However, the specified instruction has multiple
  2716. /// uses. Given this, it may actually increase register pressure to fold it
  2717. /// into the load. For example, consider this code:
  2718. ///
  2719. /// X = ...
  2720. /// Y = X+1
  2721. /// use(Y) -> nonload/store
  2722. /// Z = Y+1
  2723. /// load Z
  2724. ///
  2725. /// In this case, Y has multiple uses, and can be folded into the load of Z
  2726. /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
  2727. /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
  2728. /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
  2729. /// number of computations either.
  2730. ///
  2731. /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
  2732. /// X was live across 'load Z' for other reasons, we actually *would* want to
  2733. /// fold the addressing mode in the Z case. This would make Y die earlier.
  2734. bool AddressingModeMatcher::
  2735. IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
  2736. ExtAddrMode &AMAfter) {
  2737. if (IgnoreProfitability) return true;
  2738. // AMBefore is the addressing mode before this instruction was folded into it,
  2739. // and AMAfter is the addressing mode after the instruction was folded. Get
  2740. // the set of registers referenced by AMAfter and subtract out those
  2741. // referenced by AMBefore: this is the set of values which folding in this
  2742. // address extends the lifetime of.
  2743. //
  2744. // Note that there are only two potential values being referenced here,
  2745. // BaseReg and ScaleReg (global addresses are always available, as are any
  2746. // folded immediates).
  2747. Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
  2748. // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
  2749. // lifetime wasn't extended by adding this instruction.
  2750. if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
  2751. BaseReg = nullptr;
  2752. if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
  2753. ScaledReg = nullptr;
  2754. // If folding this instruction (and it's subexprs) didn't extend any live
  2755. // ranges, we're ok with it.
  2756. if (!BaseReg && !ScaledReg)
  2757. return true;
  2758. // If all uses of this instruction are ultimately load/store/inlineasm's,
  2759. // check to see if their addressing modes will include this instruction. If
  2760. // so, we can fold it into all uses, so it doesn't matter if it has multiple
  2761. // uses.
  2762. SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
  2763. SmallPtrSet<Instruction*, 16> ConsideredInsts;
  2764. if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
  2765. return false; // Has a non-memory, non-foldable use!
  2766. // Now that we know that all uses of this instruction are part of a chain of
  2767. // computation involving only operations that could theoretically be folded
  2768. // into a memory use, loop over each of these uses and see if they could
  2769. // *actually* fold the instruction.
  2770. SmallVector<Instruction*, 32> MatchedAddrModeInsts;
  2771. for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
  2772. Instruction *User = MemoryUses[i].first;
  2773. unsigned OpNo = MemoryUses[i].second;
  2774. // Get the access type of this use. If the use isn't a pointer, we don't
  2775. // know what it accesses.
  2776. Value *Address = User->getOperand(OpNo);
  2777. PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
  2778. if (!AddrTy)
  2779. return false;
  2780. Type *AddressAccessTy = AddrTy->getElementType();
  2781. unsigned AS = AddrTy->getAddressSpace();
  2782. // Do a match against the root of this address, ignoring profitability. This
  2783. // will tell us if the addressing mode for the memory operation will
  2784. // *actually* cover the shared instruction.
  2785. ExtAddrMode Result;
  2786. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  2787. TPT.getRestorationPoint();
  2788. AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
  2789. MemoryInst, Result, InsertedInsts,
  2790. PromotedInsts, TPT);
  2791. Matcher.IgnoreProfitability = true;
  2792. bool Success = Matcher.MatchAddr(Address, 0);
  2793. (void)Success; assert(Success && "Couldn't select *anything*?");
  2794. // The match was to check the profitability, the changes made are not
  2795. // part of the original matcher. Therefore, they should be dropped
  2796. // otherwise the original matcher will not present the right state.
  2797. TPT.rollback(LastKnownGood);
  2798. // If the match didn't cover I, then it won't be shared by it.
  2799. if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
  2800. I) == MatchedAddrModeInsts.end())
  2801. return false;
  2802. MatchedAddrModeInsts.clear();
  2803. }
  2804. return true;
  2805. }
  2806. } // end anonymous namespace
  2807. /// IsNonLocalValue - Return true if the specified values are defined in a
  2808. /// different basic block than BB.
  2809. static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
  2810. if (Instruction *I = dyn_cast<Instruction>(V))
  2811. return I->getParent() != BB;
  2812. return false;
  2813. }
  2814. /// OptimizeMemoryInst - Load and Store Instructions often have
  2815. /// addressing modes that can do significant amounts of computation. As such,
  2816. /// instruction selection will try to get the load or store to do as much
  2817. /// computation as possible for the program. The problem is that isel can only
  2818. /// see within a single block. As such, we sink as much legal addressing mode
  2819. /// stuff into the block as possible.
  2820. ///
  2821. /// This method is used to optimize both load/store and inline asms with memory
  2822. /// operands.
  2823. bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
  2824. Type *AccessTy, unsigned AddrSpace) {
  2825. Value *Repl = Addr;
  2826. // Try to collapse single-value PHI nodes. This is necessary to undo
  2827. // unprofitable PRE transformations.
  2828. SmallVector<Value*, 8> worklist;
  2829. SmallPtrSet<Value*, 16> Visited;
  2830. worklist.push_back(Addr);
  2831. // Use a worklist to iteratively look through PHI nodes, and ensure that
  2832. // the addressing mode obtained from the non-PHI roots of the graph
  2833. // are equivalent.
  2834. Value *Consensus = nullptr;
  2835. unsigned NumUsesConsensus = 0;
  2836. bool IsNumUsesConsensusValid = false;
  2837. SmallVector<Instruction*, 16> AddrModeInsts;
  2838. ExtAddrMode AddrMode;
  2839. TypePromotionTransaction TPT;
  2840. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  2841. TPT.getRestorationPoint();
  2842. while (!worklist.empty()) {
  2843. Value *V = worklist.back();
  2844. worklist.pop_back();
  2845. // Break use-def graph loops.
  2846. if (!Visited.insert(V).second) {
  2847. Consensus = nullptr;
  2848. break;
  2849. }
  2850. // For a PHI node, push all of its incoming values.
  2851. if (PHINode *P = dyn_cast<PHINode>(V)) {
  2852. for (Value *IncValue : P->incoming_values())
  2853. worklist.push_back(IncValue);
  2854. continue;
  2855. }
  2856. // For non-PHIs, determine the addressing mode being computed.
  2857. SmallVector<Instruction*, 16> NewAddrModeInsts;
  2858. ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
  2859. V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
  2860. InsertedInsts, PromotedInsts, TPT);
  2861. // This check is broken into two cases with very similar code to avoid using
  2862. // getNumUses() as much as possible. Some values have a lot of uses, so
  2863. // calling getNumUses() unconditionally caused a significant compile-time
  2864. // regression.
  2865. if (!Consensus) {
  2866. Consensus = V;
  2867. AddrMode = NewAddrMode;
  2868. AddrModeInsts = NewAddrModeInsts;
  2869. continue;
  2870. } else if (NewAddrMode == AddrMode) {
  2871. if (!IsNumUsesConsensusValid) {
  2872. NumUsesConsensus = Consensus->getNumUses();
  2873. IsNumUsesConsensusValid = true;
  2874. }
  2875. // Ensure that the obtained addressing mode is equivalent to that obtained
  2876. // for all other roots of the PHI traversal. Also, when choosing one
  2877. // such root as representative, select the one with the most uses in order
  2878. // to keep the cost modeling heuristics in AddressingModeMatcher
  2879. // applicable.
  2880. unsigned NumUses = V->getNumUses();
  2881. if (NumUses > NumUsesConsensus) {
  2882. Consensus = V;
  2883. NumUsesConsensus = NumUses;
  2884. AddrModeInsts = NewAddrModeInsts;
  2885. }
  2886. continue;
  2887. }
  2888. Consensus = nullptr;
  2889. break;
  2890. }
  2891. // If the addressing mode couldn't be determined, or if multiple different
  2892. // ones were determined, bail out now.
  2893. if (!Consensus) {
  2894. TPT.rollback(LastKnownGood);
  2895. return false;
  2896. }
  2897. TPT.commit();
  2898. // Check to see if any of the instructions supersumed by this addr mode are
  2899. // non-local to I's BB.
  2900. bool AnyNonLocal = false;
  2901. for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
  2902. if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
  2903. AnyNonLocal = true;
  2904. break;
  2905. }
  2906. }
  2907. // If all the instructions matched are already in this BB, don't do anything.
  2908. if (!AnyNonLocal) {
  2909. DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
  2910. return false;
  2911. }
  2912. // Insert this computation right after this user. Since our caller is
  2913. // scanning from the top of the BB to the bottom, reuse of the expr are
  2914. // guaranteed to happen later.
  2915. IRBuilder<> Builder(MemoryInst);
  2916. // Now that we determined the addressing expression we want to use and know
  2917. // that we have to sink it into this block. Check to see if we have already
  2918. // done this for some other load/store instr in this block. If so, reuse the
  2919. // computation.
  2920. Value *&SunkAddr = SunkAddrs[Addr];
  2921. if (SunkAddr) {
  2922. DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
  2923. << *MemoryInst << "\n");
  2924. if (SunkAddr->getType() != Addr->getType())
  2925. SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
  2926. } else if (AddrSinkUsingGEPs ||
  2927. (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
  2928. TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
  2929. ->useAA())) {
  2930. // By default, we use the GEP-based method when AA is used later. This
  2931. // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
  2932. DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
  2933. << *MemoryInst << "\n");
  2934. Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
  2935. Value *ResultPtr = nullptr, *ResultIndex = nullptr;
  2936. // First, find the pointer.
  2937. if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
  2938. ResultPtr = AddrMode.BaseReg;
  2939. AddrMode.BaseReg = nullptr;
  2940. }
  2941. if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
  2942. // We can't add more than one pointer together, nor can we scale a
  2943. // pointer (both of which seem meaningless).
  2944. if (ResultPtr || AddrMode.Scale != 1)
  2945. return false;
  2946. ResultPtr = AddrMode.ScaledReg;
  2947. AddrMode.Scale = 0;
  2948. }
  2949. if (AddrMode.BaseGV) {
  2950. if (ResultPtr)
  2951. return false;
  2952. ResultPtr = AddrMode.BaseGV;
  2953. }
  2954. // If the real base value actually came from an inttoptr, then the matcher
  2955. // will look through it and provide only the integer value. In that case,
  2956. // use it here.
  2957. if (!ResultPtr && AddrMode.BaseReg) {
  2958. ResultPtr =
  2959. Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
  2960. AddrMode.BaseReg = nullptr;
  2961. } else if (!ResultPtr && AddrMode.Scale == 1) {
  2962. ResultPtr =
  2963. Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
  2964. AddrMode.Scale = 0;
  2965. }
  2966. if (!ResultPtr &&
  2967. !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
  2968. SunkAddr = Constant::getNullValue(Addr->getType());
  2969. } else if (!ResultPtr) {
  2970. return false;
  2971. } else {
  2972. Type *I8PtrTy =
  2973. Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
  2974. Type *I8Ty = Builder.getInt8Ty();
  2975. // Start with the base register. Do this first so that subsequent address
  2976. // matching finds it last, which will prevent it from trying to match it
  2977. // as the scaled value in case it happens to be a mul. That would be
  2978. // problematic if we've sunk a different mul for the scale, because then
  2979. // we'd end up sinking both muls.
  2980. if (AddrMode.BaseReg) {
  2981. Value *V = AddrMode.BaseReg;
  2982. if (V->getType() != IntPtrTy)
  2983. V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
  2984. ResultIndex = V;
  2985. }
  2986. // Add the scale value.
  2987. if (AddrMode.Scale) {
  2988. Value *V = AddrMode.ScaledReg;
  2989. if (V->getType() == IntPtrTy) {
  2990. // done.
  2991. } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
  2992. cast<IntegerType>(V->getType())->getBitWidth()) {
  2993. V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
  2994. } else {
  2995. // It is only safe to sign extend the BaseReg if we know that the math
  2996. // required to create it did not overflow before we extend it. Since
  2997. // the original IR value was tossed in favor of a constant back when
  2998. // the AddrMode was created we need to bail out gracefully if widths
  2999. // do not match instead of extending it.
  3000. Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
  3001. if (I && (ResultIndex != AddrMode.BaseReg))
  3002. I->eraseFromParent();
  3003. return false;
  3004. }
  3005. if (AddrMode.Scale != 1)
  3006. V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
  3007. "sunkaddr");
  3008. if (ResultIndex)
  3009. ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
  3010. else
  3011. ResultIndex = V;
  3012. }
  3013. // Add in the Base Offset if present.
  3014. if (AddrMode.BaseOffs) {
  3015. Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
  3016. if (ResultIndex) {
  3017. // We need to add this separately from the scale above to help with
  3018. // SDAG consecutive load/store merging.
  3019. if (ResultPtr->getType() != I8PtrTy)
  3020. ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
  3021. ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
  3022. }
  3023. ResultIndex = V;
  3024. }
  3025. if (!ResultIndex) {
  3026. SunkAddr = ResultPtr;
  3027. } else {
  3028. if (ResultPtr->getType() != I8PtrTy)
  3029. ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
  3030. SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
  3031. }
  3032. if (SunkAddr->getType() != Addr->getType())
  3033. SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
  3034. }
  3035. } else {
  3036. DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
  3037. << *MemoryInst << "\n");
  3038. Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
  3039. Value *Result = nullptr;
  3040. // Start with the base register. Do this first so that subsequent address
  3041. // matching finds it last, which will prevent it from trying to match it
  3042. // as the scaled value in case it happens to be a mul. That would be
  3043. // problematic if we've sunk a different mul for the scale, because then
  3044. // we'd end up sinking both muls.
  3045. if (AddrMode.BaseReg) {
  3046. Value *V = AddrMode.BaseReg;
  3047. if (V->getType()->isPointerTy())
  3048. V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
  3049. if (V->getType() != IntPtrTy)
  3050. V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
  3051. Result = V;
  3052. }
  3053. // Add the scale value.
  3054. if (AddrMode.Scale) {
  3055. Value *V = AddrMode.ScaledReg;
  3056. if (V->getType() == IntPtrTy) {
  3057. // done.
  3058. } else if (V->getType()->isPointerTy()) {
  3059. V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
  3060. } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
  3061. cast<IntegerType>(V->getType())->getBitWidth()) {
  3062. V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
  3063. } else {
  3064. // It is only safe to sign extend the BaseReg if we know that the math
  3065. // required to create it did not overflow before we extend it. Since
  3066. // the original IR value was tossed in favor of a constant back when
  3067. // the AddrMode was created we need to bail out gracefully if widths
  3068. // do not match instead of extending it.
  3069. Instruction *I = dyn_cast_or_null<Instruction>(Result);
  3070. if (I && (Result != AddrMode.BaseReg))
  3071. I->eraseFromParent();
  3072. return false;
  3073. }
  3074. if (AddrMode.Scale != 1)
  3075. V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
  3076. "sunkaddr");
  3077. if (Result)
  3078. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  3079. else
  3080. Result = V;
  3081. }
  3082. // Add in the BaseGV if present.
  3083. if (AddrMode.BaseGV) {
  3084. Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
  3085. if (Result)
  3086. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  3087. else
  3088. Result = V;
  3089. }
  3090. // Add in the Base Offset if present.
  3091. if (AddrMode.BaseOffs) {
  3092. Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
  3093. if (Result)
  3094. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  3095. else
  3096. Result = V;
  3097. }
  3098. if (!Result)
  3099. SunkAddr = Constant::getNullValue(Addr->getType());
  3100. else
  3101. SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
  3102. }
  3103. MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
  3104. // If we have no uses, recursively delete the value and all dead instructions
  3105. // using it.
  3106. if (Repl->use_empty()) {
  3107. // This can cause recursive deletion, which can invalidate our iterator.
  3108. // Use a WeakVH to hold onto it in case this happens.
  3109. WeakVH IterHandle(CurInstIterator);
  3110. BasicBlock *BB = CurInstIterator->getParent();
  3111. RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
  3112. if (IterHandle != CurInstIterator) {
  3113. // If the iterator instruction was recursively deleted, start over at the
  3114. // start of the block.
  3115. CurInstIterator = BB->begin();
  3116. SunkAddrs.clear();
  3117. }
  3118. }
  3119. ++NumMemoryInsts;
  3120. return true;
  3121. }
  3122. /// OptimizeInlineAsmInst - If there are any memory operands, use
  3123. /// OptimizeMemoryInst to sink their address computing into the block when
  3124. /// possible / profitable.
  3125. bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
  3126. bool MadeChange = false;
  3127. const TargetRegisterInfo *TRI =
  3128. TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
  3129. TargetLowering::AsmOperandInfoVector TargetConstraints =
  3130. TLI->ParseConstraints(*DL, TRI, CS);
  3131. unsigned ArgNo = 0;
  3132. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  3133. TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
  3134. // Compute the constraint code and ConstraintType to use.
  3135. TLI->ComputeConstraintToUse(OpInfo, SDValue());
  3136. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  3137. OpInfo.isIndirect) {
  3138. Value *OpVal = CS->getArgOperand(ArgNo++);
  3139. MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
  3140. } else if (OpInfo.Type == InlineAsm::isInput)
  3141. ArgNo++;
  3142. }
  3143. return MadeChange;
  3144. }
  3145. /// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
  3146. /// sign extensions.
  3147. static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
  3148. assert(!Inst->use_empty() && "Input must have at least one use");
  3149. const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
  3150. bool IsSExt = isa<SExtInst>(FirstUser);
  3151. Type *ExtTy = FirstUser->getType();
  3152. for (const User *U : Inst->users()) {
  3153. const Instruction *UI = cast<Instruction>(U);
  3154. if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
  3155. return false;
  3156. Type *CurTy = UI->getType();
  3157. // Same input and output types: Same instruction after CSE.
  3158. if (CurTy == ExtTy)
  3159. continue;
  3160. // If IsSExt is true, we are in this situation:
  3161. // a = Inst
  3162. // b = sext ty1 a to ty2
  3163. // c = sext ty1 a to ty3
  3164. // Assuming ty2 is shorter than ty3, this could be turned into:
  3165. // a = Inst
  3166. // b = sext ty1 a to ty2
  3167. // c = sext ty2 b to ty3
  3168. // However, the last sext is not free.
  3169. if (IsSExt)
  3170. return false;
  3171. // This is a ZExt, maybe this is free to extend from one type to another.
  3172. // In that case, we would not account for a different use.
  3173. Type *NarrowTy;
  3174. Type *LargeTy;
  3175. if (ExtTy->getScalarType()->getIntegerBitWidth() >
  3176. CurTy->getScalarType()->getIntegerBitWidth()) {
  3177. NarrowTy = CurTy;
  3178. LargeTy = ExtTy;
  3179. } else {
  3180. NarrowTy = ExtTy;
  3181. LargeTy = CurTy;
  3182. }
  3183. if (!TLI.isZExtFree(NarrowTy, LargeTy))
  3184. return false;
  3185. }
  3186. // All uses are the same or can be derived from one another for free.
  3187. return true;
  3188. }
  3189. /// \brief Try to form ExtLd by promoting \p Exts until they reach a
  3190. /// load instruction.
  3191. /// If an ext(load) can be formed, it is returned via \p LI for the load
  3192. /// and \p Inst for the extension.
  3193. /// Otherwise LI == nullptr and Inst == nullptr.
  3194. /// When some promotion happened, \p TPT contains the proper state to
  3195. /// revert them.
  3196. ///
  3197. /// \return true when promoting was necessary to expose the ext(load)
  3198. /// opportunity, false otherwise.
  3199. ///
  3200. /// Example:
  3201. /// \code
  3202. /// %ld = load i32* %addr
  3203. /// %add = add nuw i32 %ld, 4
  3204. /// %zext = zext i32 %add to i64
  3205. /// \endcode
  3206. /// =>
  3207. /// \code
  3208. /// %ld = load i32* %addr
  3209. /// %zext = zext i32 %ld to i64
  3210. /// %add = add nuw i64 %zext, 4
  3211. /// \encode
  3212. /// Thanks to the promotion, we can match zext(load i32*) to i64.
  3213. bool CodeGenPrepare::ExtLdPromotion(TypePromotionTransaction &TPT,
  3214. LoadInst *&LI, Instruction *&Inst,
  3215. const SmallVectorImpl<Instruction *> &Exts,
  3216. unsigned CreatedInstsCost = 0) {
  3217. // Iterate over all the extensions to see if one form an ext(load).
  3218. for (auto I : Exts) {
  3219. // Check if we directly have ext(load).
  3220. if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
  3221. Inst = I;
  3222. // No promotion happened here.
  3223. return false;
  3224. }
  3225. // Check whether or not we want to do any promotion.
  3226. if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
  3227. continue;
  3228. // Get the action to perform the promotion.
  3229. TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
  3230. I, InsertedInsts, *TLI, PromotedInsts);
  3231. // Check if we can promote.
  3232. if (!TPH)
  3233. continue;
  3234. // Save the current state.
  3235. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3236. TPT.getRestorationPoint();
  3237. SmallVector<Instruction *, 4> NewExts;
  3238. unsigned NewCreatedInstsCost = 0;
  3239. unsigned ExtCost = !TLI->isExtFree(I);
  3240. // Promote.
  3241. Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
  3242. &NewExts, nullptr, *TLI);
  3243. assert(PromotedVal &&
  3244. "TypePromotionHelper should have filtered out those cases");
  3245. // We would be able to merge only one extension in a load.
  3246. // Therefore, if we have more than 1 new extension we heuristically
  3247. // cut this search path, because it means we degrade the code quality.
  3248. // With exactly 2, the transformation is neutral, because we will merge
  3249. // one extension but leave one. However, we optimistically keep going,
  3250. // because the new extension may be removed too.
  3251. long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
  3252. TotalCreatedInstsCost -= ExtCost;
  3253. if (!StressExtLdPromotion &&
  3254. (TotalCreatedInstsCost > 1 ||
  3255. !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
  3256. // The promotion is not profitable, rollback to the previous state.
  3257. TPT.rollback(LastKnownGood);
  3258. continue;
  3259. }
  3260. // The promotion is profitable.
  3261. // Check if it exposes an ext(load).
  3262. (void)ExtLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
  3263. if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
  3264. // If we have created a new extension, i.e., now we have two
  3265. // extensions. We must make sure one of them is merged with
  3266. // the load, otherwise we may degrade the code quality.
  3267. (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
  3268. // Promotion happened.
  3269. return true;
  3270. // If this does not help to expose an ext(load) then, rollback.
  3271. TPT.rollback(LastKnownGood);
  3272. }
  3273. // None of the extension can form an ext(load).
  3274. LI = nullptr;
  3275. Inst = nullptr;
  3276. return false;
  3277. }
  3278. /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
  3279. /// basic block as the load, unless conditions are unfavorable. This allows
  3280. /// SelectionDAG to fold the extend into the load.
  3281. /// \p I[in/out] the extension may be modified during the process if some
  3282. /// promotions apply.
  3283. ///
  3284. bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *&I) {
  3285. // Try to promote a chain of computation if it allows to form
  3286. // an extended load.
  3287. TypePromotionTransaction TPT;
  3288. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3289. TPT.getRestorationPoint();
  3290. SmallVector<Instruction *, 1> Exts;
  3291. Exts.push_back(I);
  3292. // Look for a load being extended.
  3293. LoadInst *LI = nullptr;
  3294. Instruction *OldExt = I;
  3295. bool HasPromoted = ExtLdPromotion(TPT, LI, I, Exts);
  3296. if (!LI || !I) {
  3297. assert(!HasPromoted && !LI && "If we did not match any load instruction "
  3298. "the code must remain the same");
  3299. I = OldExt;
  3300. return false;
  3301. }
  3302. // If they're already in the same block, there's nothing to do.
  3303. // Make the cheap checks first if we did not promote.
  3304. // If we promoted, we need to check if it is indeed profitable.
  3305. if (!HasPromoted && LI->getParent() == I->getParent())
  3306. return false;
  3307. EVT VT = TLI->getValueType(*DL, I->getType());
  3308. EVT LoadVT = TLI->getValueType(*DL, LI->getType());
  3309. // If the load has other users and the truncate is not free, this probably
  3310. // isn't worthwhile.
  3311. if (!LI->hasOneUse() && TLI &&
  3312. (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
  3313. !TLI->isTruncateFree(I->getType(), LI->getType())) {
  3314. I = OldExt;
  3315. TPT.rollback(LastKnownGood);
  3316. return false;
  3317. }
  3318. // Check whether the target supports casts folded into loads.
  3319. unsigned LType;
  3320. if (isa<ZExtInst>(I))
  3321. LType = ISD::ZEXTLOAD;
  3322. else {
  3323. assert(isa<SExtInst>(I) && "Unexpected ext type!");
  3324. LType = ISD::SEXTLOAD;
  3325. }
  3326. if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
  3327. I = OldExt;
  3328. TPT.rollback(LastKnownGood);
  3329. return false;
  3330. }
  3331. // Move the extend into the same block as the load, so that SelectionDAG
  3332. // can fold it.
  3333. TPT.commit();
  3334. I->removeFromParent();
  3335. I->insertAfter(LI);
  3336. ++NumExtsMoved;
  3337. return true;
  3338. }
  3339. bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
  3340. BasicBlock *DefBB = I->getParent();
  3341. // If the result of a {s|z}ext and its source are both live out, rewrite all
  3342. // other uses of the source with result of extension.
  3343. Value *Src = I->getOperand(0);
  3344. if (Src->hasOneUse())
  3345. return false;
  3346. // Only do this xform if truncating is free.
  3347. if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
  3348. return false;
  3349. // Only safe to perform the optimization if the source is also defined in
  3350. // this block.
  3351. if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
  3352. return false;
  3353. bool DefIsLiveOut = false;
  3354. for (User *U : I->users()) {
  3355. Instruction *UI = cast<Instruction>(U);
  3356. // Figure out which BB this ext is used in.
  3357. BasicBlock *UserBB = UI->getParent();
  3358. if (UserBB == DefBB) continue;
  3359. DefIsLiveOut = true;
  3360. break;
  3361. }
  3362. if (!DefIsLiveOut)
  3363. return false;
  3364. // Make sure none of the uses are PHI nodes.
  3365. for (User *U : Src->users()) {
  3366. Instruction *UI = cast<Instruction>(U);
  3367. BasicBlock *UserBB = UI->getParent();
  3368. if (UserBB == DefBB) continue;
  3369. // Be conservative. We don't want this xform to end up introducing
  3370. // reloads just before load / store instructions.
  3371. if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
  3372. return false;
  3373. }
  3374. // InsertedTruncs - Only insert one trunc in each block once.
  3375. DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
  3376. bool MadeChange = false;
  3377. for (Use &U : Src->uses()) {
  3378. Instruction *User = cast<Instruction>(U.getUser());
  3379. // Figure out which BB this ext is used in.
  3380. BasicBlock *UserBB = User->getParent();
  3381. if (UserBB == DefBB) continue;
  3382. // Both src and def are live in this block. Rewrite the use.
  3383. Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
  3384. if (!InsertedTrunc) {
  3385. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  3386. InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
  3387. InsertedInsts.insert(InsertedTrunc);
  3388. }
  3389. // Replace a use of the {s|z}ext source with a use of the result.
  3390. U = InsertedTrunc;
  3391. ++NumExtUses;
  3392. MadeChange = true;
  3393. }
  3394. return MadeChange;
  3395. }
  3396. /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
  3397. /// turned into an explicit branch.
  3398. static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
  3399. // FIXME: This should use the same heuristics as IfConversion to determine
  3400. // whether a select is better represented as a branch. This requires that
  3401. // branch probability metadata is preserved for the select, which is not the
  3402. // case currently.
  3403. CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
  3404. // If the branch is predicted right, an out of order CPU can avoid blocking on
  3405. // the compare. Emit cmovs on compares with a memory operand as branches to
  3406. // avoid stalls on the load from memory. If the compare has more than one use
  3407. // there's probably another cmov or setcc around so it's not worth emitting a
  3408. // branch.
  3409. if (!Cmp)
  3410. return false;
  3411. Value *CmpOp0 = Cmp->getOperand(0);
  3412. Value *CmpOp1 = Cmp->getOperand(1);
  3413. // We check that the memory operand has one use to avoid uses of the loaded
  3414. // value directly after the compare, making branches unprofitable.
  3415. return Cmp->hasOneUse() &&
  3416. ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
  3417. (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
  3418. }
  3419. /// If we have a SelectInst that will likely profit from branch prediction,
  3420. /// turn it into a branch.
  3421. bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
  3422. bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
  3423. // Can we convert the 'select' to CF ?
  3424. if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
  3425. return false;
  3426. TargetLowering::SelectSupportKind SelectKind;
  3427. if (VectorCond)
  3428. SelectKind = TargetLowering::VectorMaskSelect;
  3429. else if (SI->getType()->isVectorTy())
  3430. SelectKind = TargetLowering::ScalarCondVectorVal;
  3431. else
  3432. SelectKind = TargetLowering::ScalarValSelect;
  3433. // Do we have efficient codegen support for this kind of 'selects' ?
  3434. if (TLI->isSelectSupported(SelectKind)) {
  3435. // We have efficient codegen support for the select instruction.
  3436. // Check if it is profitable to keep this 'select'.
  3437. if (!TLI->isPredictableSelectExpensive() ||
  3438. !isFormingBranchFromSelectProfitable(SI))
  3439. return false;
  3440. }
  3441. ModifiedDT = true;
  3442. // First, we split the block containing the select into 2 blocks.
  3443. BasicBlock *StartBlock = SI->getParent();
  3444. BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
  3445. BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
  3446. // Create a new block serving as the landing pad for the branch.
  3447. BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
  3448. NextBlock->getParent(), NextBlock);
  3449. // Move the unconditional branch from the block with the select in it into our
  3450. // landing pad block.
  3451. StartBlock->getTerminator()->eraseFromParent();
  3452. BranchInst::Create(NextBlock, SmallBlock);
  3453. // Insert the real conditional branch based on the original condition.
  3454. BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
  3455. // The select itself is replaced with a PHI Node.
  3456. PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
  3457. PN->takeName(SI);
  3458. PN->addIncoming(SI->getTrueValue(), StartBlock);
  3459. PN->addIncoming(SI->getFalseValue(), SmallBlock);
  3460. SI->replaceAllUsesWith(PN);
  3461. SI->eraseFromParent();
  3462. // Instruct OptimizeBlock to skip to the next block.
  3463. CurInstIterator = StartBlock->end();
  3464. ++NumSelectsExpanded;
  3465. return true;
  3466. }
  3467. static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
  3468. SmallVector<int, 16> Mask(SVI->getShuffleMask());
  3469. int SplatElem = -1;
  3470. for (unsigned i = 0; i < Mask.size(); ++i) {
  3471. if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
  3472. return false;
  3473. SplatElem = Mask[i];
  3474. }
  3475. return true;
  3476. }
  3477. /// Some targets have expensive vector shifts if the lanes aren't all the same
  3478. /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
  3479. /// it's often worth sinking a shufflevector splat down to its use so that
  3480. /// codegen can spot all lanes are identical.
  3481. bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
  3482. BasicBlock *DefBB = SVI->getParent();
  3483. // Only do this xform if variable vector shifts are particularly expensive.
  3484. if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
  3485. return false;
  3486. // We only expect better codegen by sinking a shuffle if we can recognise a
  3487. // constant splat.
  3488. if (!isBroadcastShuffle(SVI))
  3489. return false;
  3490. // InsertedShuffles - Only insert a shuffle in each block once.
  3491. DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
  3492. bool MadeChange = false;
  3493. for (User *U : SVI->users()) {
  3494. Instruction *UI = cast<Instruction>(U);
  3495. // Figure out which BB this ext is used in.
  3496. BasicBlock *UserBB = UI->getParent();
  3497. if (UserBB == DefBB) continue;
  3498. // For now only apply this when the splat is used by a shift instruction.
  3499. if (!UI->isShift()) continue;
  3500. // Everything checks out, sink the shuffle if the user's block doesn't
  3501. // already have a copy.
  3502. Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
  3503. if (!InsertedShuffle) {
  3504. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  3505. InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
  3506. SVI->getOperand(1),
  3507. SVI->getOperand(2), "", InsertPt);
  3508. }
  3509. UI->replaceUsesOfWith(SVI, InsertedShuffle);
  3510. MadeChange = true;
  3511. }
  3512. // If we removed all uses, nuke the shuffle.
  3513. if (SVI->use_empty()) {
  3514. SVI->eraseFromParent();
  3515. MadeChange = true;
  3516. }
  3517. return MadeChange;
  3518. }
  3519. namespace {
  3520. /// \brief Helper class to promote a scalar operation to a vector one.
  3521. /// This class is used to move downward extractelement transition.
  3522. /// E.g.,
  3523. /// a = vector_op <2 x i32>
  3524. /// b = extractelement <2 x i32> a, i32 0
  3525. /// c = scalar_op b
  3526. /// store c
  3527. ///
  3528. /// =>
  3529. /// a = vector_op <2 x i32>
  3530. /// c = vector_op a (equivalent to scalar_op on the related lane)
  3531. /// * d = extractelement <2 x i32> c, i32 0
  3532. /// * store d
  3533. /// Assuming both extractelement and store can be combine, we get rid of the
  3534. /// transition.
  3535. class VectorPromoteHelper {
  3536. /// DataLayout associated with the current module.
  3537. const DataLayout &DL;
  3538. /// Used to perform some checks on the legality of vector operations.
  3539. const TargetLowering &TLI;
  3540. /// Used to estimated the cost of the promoted chain.
  3541. const TargetTransformInfo &TTI;
  3542. /// The transition being moved downwards.
  3543. Instruction *Transition;
  3544. /// The sequence of instructions to be promoted.
  3545. SmallVector<Instruction *, 4> InstsToBePromoted;
  3546. /// Cost of combining a store and an extract.
  3547. unsigned StoreExtractCombineCost;
  3548. /// Instruction that will be combined with the transition.
  3549. Instruction *CombineInst;
  3550. /// \brief The instruction that represents the current end of the transition.
  3551. /// Since we are faking the promotion until we reach the end of the chain
  3552. /// of computation, we need a way to get the current end of the transition.
  3553. Instruction *getEndOfTransition() const {
  3554. if (InstsToBePromoted.empty())
  3555. return Transition;
  3556. return InstsToBePromoted.back();
  3557. }
  3558. /// \brief Return the index of the original value in the transition.
  3559. /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
  3560. /// c, is at index 0.
  3561. unsigned getTransitionOriginalValueIdx() const {
  3562. assert(isa<ExtractElementInst>(Transition) &&
  3563. "Other kind of transitions are not supported yet");
  3564. return 0;
  3565. }
  3566. /// \brief Return the index of the index in the transition.
  3567. /// E.g., for "extractelement <2 x i32> c, i32 0" the index
  3568. /// is at index 1.
  3569. unsigned getTransitionIdx() const {
  3570. assert(isa<ExtractElementInst>(Transition) &&
  3571. "Other kind of transitions are not supported yet");
  3572. return 1;
  3573. }
  3574. /// \brief Get the type of the transition.
  3575. /// This is the type of the original value.
  3576. /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
  3577. /// transition is <2 x i32>.
  3578. Type *getTransitionType() const {
  3579. return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
  3580. }
  3581. /// \brief Promote \p ToBePromoted by moving \p Def downward through.
  3582. /// I.e., we have the following sequence:
  3583. /// Def = Transition <ty1> a to <ty2>
  3584. /// b = ToBePromoted <ty2> Def, ...
  3585. /// =>
  3586. /// b = ToBePromoted <ty1> a, ...
  3587. /// Def = Transition <ty1> ToBePromoted to <ty2>
  3588. void promoteImpl(Instruction *ToBePromoted);
  3589. /// \brief Check whether or not it is profitable to promote all the
  3590. /// instructions enqueued to be promoted.
  3591. bool isProfitableToPromote() {
  3592. Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
  3593. unsigned Index = isa<ConstantInt>(ValIdx)
  3594. ? cast<ConstantInt>(ValIdx)->getZExtValue()
  3595. : -1;
  3596. Type *PromotedType = getTransitionType();
  3597. StoreInst *ST = cast<StoreInst>(CombineInst);
  3598. unsigned AS = ST->getPointerAddressSpace();
  3599. unsigned Align = ST->getAlignment();
  3600. // Check if this store is supported.
  3601. if (!TLI.allowsMisalignedMemoryAccesses(
  3602. TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
  3603. Align)) {
  3604. // If this is not supported, there is no way we can combine
  3605. // the extract with the store.
  3606. return false;
  3607. }
  3608. // The scalar chain of computation has to pay for the transition
  3609. // scalar to vector.
  3610. // The vector chain has to account for the combining cost.
  3611. uint64_t ScalarCost =
  3612. TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
  3613. uint64_t VectorCost = StoreExtractCombineCost;
  3614. for (const auto &Inst : InstsToBePromoted) {
  3615. // Compute the cost.
  3616. // By construction, all instructions being promoted are arithmetic ones.
  3617. // Moreover, one argument is a constant that can be viewed as a splat
  3618. // constant.
  3619. Value *Arg0 = Inst->getOperand(0);
  3620. bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
  3621. isa<ConstantFP>(Arg0);
  3622. TargetTransformInfo::OperandValueKind Arg0OVK =
  3623. IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
  3624. : TargetTransformInfo::OK_AnyValue;
  3625. TargetTransformInfo::OperandValueKind Arg1OVK =
  3626. !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
  3627. : TargetTransformInfo::OK_AnyValue;
  3628. ScalarCost += TTI.getArithmeticInstrCost(
  3629. Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
  3630. VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
  3631. Arg0OVK, Arg1OVK);
  3632. }
  3633. DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
  3634. << ScalarCost << "\nVector: " << VectorCost << '\n');
  3635. return ScalarCost > VectorCost;
  3636. }
  3637. /// \brief Generate a constant vector with \p Val with the same
  3638. /// number of elements as the transition.
  3639. /// \p UseSplat defines whether or not \p Val should be replicated
  3640. /// accross the whole vector.
  3641. /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
  3642. /// otherwise we generate a vector with as many undef as possible:
  3643. /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
  3644. /// used at the index of the extract.
  3645. Value *getConstantVector(Constant *Val, bool UseSplat) const {
  3646. unsigned ExtractIdx = UINT_MAX;
  3647. if (!UseSplat) {
  3648. // If we cannot determine where the constant must be, we have to
  3649. // use a splat constant.
  3650. Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
  3651. if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
  3652. ExtractIdx = CstVal->getSExtValue();
  3653. else
  3654. UseSplat = true;
  3655. }
  3656. unsigned End = getTransitionType()->getVectorNumElements();
  3657. if (UseSplat)
  3658. return ConstantVector::getSplat(End, Val);
  3659. SmallVector<Constant *, 4> ConstVec;
  3660. UndefValue *UndefVal = UndefValue::get(Val->getType());
  3661. for (unsigned Idx = 0; Idx != End; ++Idx) {
  3662. if (Idx == ExtractIdx)
  3663. ConstVec.push_back(Val);
  3664. else
  3665. ConstVec.push_back(UndefVal);
  3666. }
  3667. return ConstantVector::get(ConstVec);
  3668. }
  3669. /// \brief Check if promoting to a vector type an operand at \p OperandIdx
  3670. /// in \p Use can trigger undefined behavior.
  3671. static bool canCauseUndefinedBehavior(const Instruction *Use,
  3672. unsigned OperandIdx) {
  3673. // This is not safe to introduce undef when the operand is on
  3674. // the right hand side of a division-like instruction.
  3675. if (OperandIdx != 1)
  3676. return false;
  3677. switch (Use->getOpcode()) {
  3678. default:
  3679. return false;
  3680. case Instruction::SDiv:
  3681. case Instruction::UDiv:
  3682. case Instruction::SRem:
  3683. case Instruction::URem:
  3684. return true;
  3685. case Instruction::FDiv:
  3686. case Instruction::FRem:
  3687. return !Use->hasNoNaNs();
  3688. }
  3689. llvm_unreachable(nullptr);
  3690. }
  3691. public:
  3692. VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
  3693. const TargetTransformInfo &TTI, Instruction *Transition,
  3694. unsigned CombineCost)
  3695. : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
  3696. StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
  3697. assert(Transition && "Do not know how to promote null");
  3698. }
  3699. /// \brief Check if we can promote \p ToBePromoted to \p Type.
  3700. bool canPromote(const Instruction *ToBePromoted) const {
  3701. // We could support CastInst too.
  3702. return isa<BinaryOperator>(ToBePromoted);
  3703. }
  3704. /// \brief Check if it is profitable to promote \p ToBePromoted
  3705. /// by moving downward the transition through.
  3706. bool shouldPromote(const Instruction *ToBePromoted) const {
  3707. // Promote only if all the operands can be statically expanded.
  3708. // Indeed, we do not want to introduce any new kind of transitions.
  3709. for (const Use &U : ToBePromoted->operands()) {
  3710. const Value *Val = U.get();
  3711. if (Val == getEndOfTransition()) {
  3712. // If the use is a division and the transition is on the rhs,
  3713. // we cannot promote the operation, otherwise we may create a
  3714. // division by zero.
  3715. if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
  3716. return false;
  3717. continue;
  3718. }
  3719. if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
  3720. !isa<ConstantFP>(Val))
  3721. return false;
  3722. }
  3723. // Check that the resulting operation is legal.
  3724. int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
  3725. if (!ISDOpcode)
  3726. return false;
  3727. return StressStoreExtract ||
  3728. TLI.isOperationLegalOrCustom(
  3729. ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
  3730. }
  3731. /// \brief Check whether or not \p Use can be combined
  3732. /// with the transition.
  3733. /// I.e., is it possible to do Use(Transition) => AnotherUse?
  3734. bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
  3735. /// \brief Record \p ToBePromoted as part of the chain to be promoted.
  3736. void enqueueForPromotion(Instruction *ToBePromoted) {
  3737. InstsToBePromoted.push_back(ToBePromoted);
  3738. }
  3739. /// \brief Set the instruction that will be combined with the transition.
  3740. void recordCombineInstruction(Instruction *ToBeCombined) {
  3741. assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
  3742. CombineInst = ToBeCombined;
  3743. }
  3744. /// \brief Promote all the instructions enqueued for promotion if it is
  3745. /// is profitable.
  3746. /// \return True if the promotion happened, false otherwise.
  3747. bool promote() {
  3748. // Check if there is something to promote.
  3749. // Right now, if we do not have anything to combine with,
  3750. // we assume the promotion is not profitable.
  3751. if (InstsToBePromoted.empty() || !CombineInst)
  3752. return false;
  3753. // Check cost.
  3754. if (!StressStoreExtract && !isProfitableToPromote())
  3755. return false;
  3756. // Promote.
  3757. for (auto &ToBePromoted : InstsToBePromoted)
  3758. promoteImpl(ToBePromoted);
  3759. InstsToBePromoted.clear();
  3760. return true;
  3761. }
  3762. };
  3763. } // End of anonymous namespace.
  3764. void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
  3765. // At this point, we know that all the operands of ToBePromoted but Def
  3766. // can be statically promoted.
  3767. // For Def, we need to use its parameter in ToBePromoted:
  3768. // b = ToBePromoted ty1 a
  3769. // Def = Transition ty1 b to ty2
  3770. // Move the transition down.
  3771. // 1. Replace all uses of the promoted operation by the transition.
  3772. // = ... b => = ... Def.
  3773. assert(ToBePromoted->getType() == Transition->getType() &&
  3774. "The type of the result of the transition does not match "
  3775. "the final type");
  3776. ToBePromoted->replaceAllUsesWith(Transition);
  3777. // 2. Update the type of the uses.
  3778. // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
  3779. Type *TransitionTy = getTransitionType();
  3780. ToBePromoted->mutateType(TransitionTy);
  3781. // 3. Update all the operands of the promoted operation with promoted
  3782. // operands.
  3783. // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
  3784. for (Use &U : ToBePromoted->operands()) {
  3785. Value *Val = U.get();
  3786. Value *NewVal = nullptr;
  3787. if (Val == Transition)
  3788. NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
  3789. else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
  3790. isa<ConstantFP>(Val)) {
  3791. // Use a splat constant if it is not safe to use undef.
  3792. NewVal = getConstantVector(
  3793. cast<Constant>(Val),
  3794. isa<UndefValue>(Val) ||
  3795. canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
  3796. } else
  3797. llvm_unreachable("Did you modified shouldPromote and forgot to update "
  3798. "this?");
  3799. ToBePromoted->setOperand(U.getOperandNo(), NewVal);
  3800. }
  3801. Transition->removeFromParent();
  3802. Transition->insertAfter(ToBePromoted);
  3803. Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
  3804. }
  3805. /// Some targets can do store(extractelement) with one instruction.
  3806. /// Try to push the extractelement towards the stores when the target
  3807. /// has this feature and this is profitable.
  3808. bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
  3809. unsigned CombineCost = UINT_MAX;
  3810. if (DisableStoreExtract || !TLI ||
  3811. (!StressStoreExtract &&
  3812. !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
  3813. Inst->getOperand(1), CombineCost)))
  3814. return false;
  3815. // At this point we know that Inst is a vector to scalar transition.
  3816. // Try to move it down the def-use chain, until:
  3817. // - We can combine the transition with its single use
  3818. // => we got rid of the transition.
  3819. // - We escape the current basic block
  3820. // => we would need to check that we are moving it at a cheaper place and
  3821. // we do not do that for now.
  3822. BasicBlock *Parent = Inst->getParent();
  3823. DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
  3824. VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
  3825. // If the transition has more than one use, assume this is not going to be
  3826. // beneficial.
  3827. while (Inst->hasOneUse()) {
  3828. Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
  3829. DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
  3830. if (ToBePromoted->getParent() != Parent) {
  3831. DEBUG(dbgs() << "Instruction to promote is in a different block ("
  3832. << ToBePromoted->getParent()->getName()
  3833. << ") than the transition (" << Parent->getName() << ").\n");
  3834. return false;
  3835. }
  3836. if (VPH.canCombine(ToBePromoted)) {
  3837. DEBUG(dbgs() << "Assume " << *Inst << '\n'
  3838. << "will be combined with: " << *ToBePromoted << '\n');
  3839. VPH.recordCombineInstruction(ToBePromoted);
  3840. bool Changed = VPH.promote();
  3841. NumStoreExtractExposed += Changed;
  3842. return Changed;
  3843. }
  3844. DEBUG(dbgs() << "Try promoting.\n");
  3845. if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
  3846. return false;
  3847. DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
  3848. VPH.enqueueForPromotion(ToBePromoted);
  3849. Inst = ToBePromoted;
  3850. }
  3851. return false;
  3852. }
  3853. bool CodeGenPrepare::OptimizeInst(Instruction *I, bool& ModifiedDT) {
  3854. // Bail out if we inserted the instruction to prevent optimizations from
  3855. // stepping on each other's toes.
  3856. if (InsertedInsts.count(I))
  3857. return false;
  3858. if (PHINode *P = dyn_cast<PHINode>(I)) {
  3859. // It is possible for very late stage optimizations (such as SimplifyCFG)
  3860. // to introduce PHI nodes too late to be cleaned up. If we detect such a
  3861. // trivial PHI, go ahead and zap it here.
  3862. if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
  3863. P->replaceAllUsesWith(V);
  3864. P->eraseFromParent();
  3865. ++NumPHIsElim;
  3866. return true;
  3867. }
  3868. return false;
  3869. }
  3870. if (CastInst *CI = dyn_cast<CastInst>(I)) {
  3871. // If the source of the cast is a constant, then this should have
  3872. // already been constant folded. The only reason NOT to constant fold
  3873. // it is if something (e.g. LSR) was careful to place the constant
  3874. // evaluation in a block other than then one that uses it (e.g. to hoist
  3875. // the address of globals out of a loop). If this is the case, we don't
  3876. // want to forward-subst the cast.
  3877. if (isa<Constant>(CI->getOperand(0)))
  3878. return false;
  3879. if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
  3880. return true;
  3881. if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
  3882. /// Sink a zext or sext into its user blocks if the target type doesn't
  3883. /// fit in one register
  3884. if (TLI &&
  3885. TLI->getTypeAction(CI->getContext(),
  3886. TLI->getValueType(*DL, CI->getType())) ==
  3887. TargetLowering::TypeExpandInteger) {
  3888. return SinkCast(CI);
  3889. } else {
  3890. bool MadeChange = MoveExtToFormExtLoad(I);
  3891. return MadeChange | OptimizeExtUses(I);
  3892. }
  3893. }
  3894. return false;
  3895. }
  3896. if (CmpInst *CI = dyn_cast<CmpInst>(I))
  3897. if (!TLI || !TLI->hasMultipleConditionRegisters())
  3898. return OptimizeCmpExpression(CI);
  3899. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  3900. if (TLI) {
  3901. unsigned AS = LI->getPointerAddressSpace();
  3902. return OptimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
  3903. }
  3904. return false;
  3905. }
  3906. if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  3907. if (TLI) {
  3908. unsigned AS = SI->getPointerAddressSpace();
  3909. return OptimizeMemoryInst(I, SI->getOperand(1),
  3910. SI->getOperand(0)->getType(), AS);
  3911. }
  3912. return false;
  3913. }
  3914. BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
  3915. if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
  3916. BinOp->getOpcode() == Instruction::LShr)) {
  3917. ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
  3918. if (TLI && CI && TLI->hasExtractBitsInsn())
  3919. return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
  3920. return false;
  3921. }
  3922. if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
  3923. if (GEPI->hasAllZeroIndices()) {
  3924. /// The GEP operand must be a pointer, so must its result -> BitCast
  3925. Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
  3926. GEPI->getName(), GEPI);
  3927. GEPI->replaceAllUsesWith(NC);
  3928. GEPI->eraseFromParent();
  3929. ++NumGEPsElim;
  3930. OptimizeInst(NC, ModifiedDT);
  3931. return true;
  3932. }
  3933. return false;
  3934. }
  3935. if (CallInst *CI = dyn_cast<CallInst>(I))
  3936. return OptimizeCallInst(CI, ModifiedDT);
  3937. if (SelectInst *SI = dyn_cast<SelectInst>(I))
  3938. return OptimizeSelectInst(SI);
  3939. if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
  3940. return OptimizeShuffleVectorInst(SVI);
  3941. if (isa<ExtractElementInst>(I))
  3942. return OptimizeExtractElementInst(I);
  3943. return false;
  3944. }
  3945. // In this pass we look for GEP and cast instructions that are used
  3946. // across basic blocks and rewrite them to improve basic-block-at-a-time
  3947. // selection.
  3948. bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
  3949. SunkAddrs.clear();
  3950. bool MadeChange = false;
  3951. CurInstIterator = BB.begin();
  3952. while (CurInstIterator != BB.end()) {
  3953. MadeChange |= OptimizeInst(CurInstIterator++, ModifiedDT);
  3954. if (ModifiedDT)
  3955. return true;
  3956. }
  3957. MadeChange |= DupRetToEnableTailCallOpts(&BB);
  3958. return MadeChange;
  3959. }
  3960. // llvm.dbg.value is far away from the value then iSel may not be able
  3961. // handle it properly. iSel will drop llvm.dbg.value if it can not
  3962. // find a node corresponding to the value.
  3963. bool CodeGenPrepare::PlaceDbgValues(Function &F) {
  3964. bool MadeChange = false;
  3965. for (BasicBlock &BB : F) {
  3966. Instruction *PrevNonDbgInst = nullptr;
  3967. for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
  3968. Instruction *Insn = BI++;
  3969. DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
  3970. // Leave dbg.values that refer to an alloca alone. These
  3971. // instrinsics describe the address of a variable (= the alloca)
  3972. // being taken. They should not be moved next to the alloca
  3973. // (and to the beginning of the scope), but rather stay close to
  3974. // where said address is used.
  3975. if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
  3976. PrevNonDbgInst = Insn;
  3977. continue;
  3978. }
  3979. Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
  3980. if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
  3981. DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
  3982. DVI->removeFromParent();
  3983. if (isa<PHINode>(VI))
  3984. DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
  3985. else
  3986. DVI->insertAfter(VI);
  3987. MadeChange = true;
  3988. ++NumDbgValueMoved;
  3989. }
  3990. }
  3991. }
  3992. return MadeChange;
  3993. }
  3994. // If there is a sequence that branches based on comparing a single bit
  3995. // against zero that can be combined into a single instruction, and the
  3996. // target supports folding these into a single instruction, sink the
  3997. // mask and compare into the branch uses. Do this before OptimizeBlock ->
  3998. // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
  3999. // searched for.
  4000. bool CodeGenPrepare::sinkAndCmp(Function &F) {
  4001. if (!EnableAndCmpSinking)
  4002. return false;
  4003. if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
  4004. return false;
  4005. bool MadeChange = false;
  4006. for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
  4007. BasicBlock *BB = I++;
  4008. // Does this BB end with the following?
  4009. // %andVal = and %val, #single-bit-set
  4010. // %icmpVal = icmp %andResult, 0
  4011. // br i1 %cmpVal label %dest1, label %dest2"
  4012. BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
  4013. if (!Brcc || !Brcc->isConditional())
  4014. continue;
  4015. ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
  4016. if (!Cmp || Cmp->getParent() != BB)
  4017. continue;
  4018. ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
  4019. if (!Zero || !Zero->isZero())
  4020. continue;
  4021. Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
  4022. if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
  4023. continue;
  4024. ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
  4025. if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
  4026. continue;
  4027. DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
  4028. // Push the "and; icmp" for any users that are conditional branches.
  4029. // Since there can only be one branch use per BB, we don't need to keep
  4030. // track of which BBs we insert into.
  4031. for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
  4032. UI != E; ) {
  4033. Use &TheUse = *UI;
  4034. // Find brcc use.
  4035. BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
  4036. ++UI;
  4037. if (!BrccUser || !BrccUser->isConditional())
  4038. continue;
  4039. BasicBlock *UserBB = BrccUser->getParent();
  4040. if (UserBB == BB) continue;
  4041. DEBUG(dbgs() << "found Brcc use\n");
  4042. // Sink the "and; icmp" to use.
  4043. MadeChange = true;
  4044. BinaryOperator *NewAnd =
  4045. BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
  4046. BrccUser);
  4047. CmpInst *NewCmp =
  4048. CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
  4049. "", BrccUser);
  4050. TheUse = NewCmp;
  4051. ++NumAndCmpsMoved;
  4052. DEBUG(BrccUser->getParent()->dump());
  4053. }
  4054. }
  4055. return MadeChange;
  4056. }
  4057. /// \brief Retrieve the probabilities of a conditional branch. Returns true on
  4058. /// success, or returns false if no or invalid metadata was found.
  4059. static bool extractBranchMetadata(BranchInst *BI,
  4060. uint64_t &ProbTrue, uint64_t &ProbFalse) {
  4061. assert(BI->isConditional() &&
  4062. "Looking for probabilities on unconditional branch?");
  4063. auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
  4064. if (!ProfileData || ProfileData->getNumOperands() != 3)
  4065. return false;
  4066. const auto *CITrue =
  4067. mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
  4068. const auto *CIFalse =
  4069. mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
  4070. if (!CITrue || !CIFalse)
  4071. return false;
  4072. ProbTrue = CITrue->getValue().getZExtValue();
  4073. ProbFalse = CIFalse->getValue().getZExtValue();
  4074. return true;
  4075. }
  4076. /// \brief Scale down both weights to fit into uint32_t.
  4077. static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
  4078. uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
  4079. uint32_t Scale = (NewMax / UINT32_MAX) + 1;
  4080. NewTrue = NewTrue / Scale;
  4081. NewFalse = NewFalse / Scale;
  4082. }
  4083. /// \brief Some targets prefer to split a conditional branch like:
  4084. /// \code
  4085. /// %0 = icmp ne i32 %a, 0
  4086. /// %1 = icmp ne i32 %b, 0
  4087. /// %or.cond = or i1 %0, %1
  4088. /// br i1 %or.cond, label %TrueBB, label %FalseBB
  4089. /// \endcode
  4090. /// into multiple branch instructions like:
  4091. /// \code
  4092. /// bb1:
  4093. /// %0 = icmp ne i32 %a, 0
  4094. /// br i1 %0, label %TrueBB, label %bb2
  4095. /// bb2:
  4096. /// %1 = icmp ne i32 %b, 0
  4097. /// br i1 %1, label %TrueBB, label %FalseBB
  4098. /// \endcode
  4099. /// This usually allows instruction selection to do even further optimizations
  4100. /// and combine the compare with the branch instruction. Currently this is
  4101. /// applied for targets which have "cheap" jump instructions.
  4102. ///
  4103. /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
  4104. ///
  4105. bool CodeGenPrepare::splitBranchCondition(Function &F) {
  4106. if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
  4107. return false;
  4108. bool MadeChange = false;
  4109. for (auto &BB : F) {
  4110. // Does this BB end with the following?
  4111. // %cond1 = icmp|fcmp|binary instruction ...
  4112. // %cond2 = icmp|fcmp|binary instruction ...
  4113. // %cond.or = or|and i1 %cond1, cond2
  4114. // br i1 %cond.or label %dest1, label %dest2"
  4115. BinaryOperator *LogicOp;
  4116. BasicBlock *TBB, *FBB;
  4117. if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
  4118. continue;
  4119. unsigned Opc;
  4120. Value *Cond1, *Cond2;
  4121. if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
  4122. m_OneUse(m_Value(Cond2)))))
  4123. Opc = Instruction::And;
  4124. else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
  4125. m_OneUse(m_Value(Cond2)))))
  4126. Opc = Instruction::Or;
  4127. else
  4128. continue;
  4129. if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
  4130. !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
  4131. continue;
  4132. DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
  4133. // Create a new BB.
  4134. auto *InsertBefore = std::next(Function::iterator(BB))
  4135. .getNodePtrUnchecked();
  4136. auto TmpBB = BasicBlock::Create(BB.getContext(),
  4137. BB.getName() + ".cond.split",
  4138. BB.getParent(), InsertBefore);
  4139. // Update original basic block by using the first condition directly by the
  4140. // branch instruction and removing the no longer needed and/or instruction.
  4141. auto *Br1 = cast<BranchInst>(BB.getTerminator());
  4142. Br1->setCondition(Cond1);
  4143. LogicOp->eraseFromParent();
  4144. // Depending on the conditon we have to either replace the true or the false
  4145. // successor of the original branch instruction.
  4146. if (Opc == Instruction::And)
  4147. Br1->setSuccessor(0, TmpBB);
  4148. else
  4149. Br1->setSuccessor(1, TmpBB);
  4150. // Fill in the new basic block.
  4151. auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
  4152. if (auto *I = dyn_cast<Instruction>(Cond2)) {
  4153. I->removeFromParent();
  4154. I->insertBefore(Br2);
  4155. }
  4156. // Update PHI nodes in both successors. The original BB needs to be
  4157. // replaced in one succesor's PHI nodes, because the branch comes now from
  4158. // the newly generated BB (NewBB). In the other successor we need to add one
  4159. // incoming edge to the PHI nodes, because both branch instructions target
  4160. // now the same successor. Depending on the original branch condition
  4161. // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
  4162. // we perfrom the correct update for the PHI nodes.
  4163. // This doesn't change the successor order of the just created branch
  4164. // instruction (or any other instruction).
  4165. if (Opc == Instruction::Or)
  4166. std::swap(TBB, FBB);
  4167. // Replace the old BB with the new BB.
  4168. for (auto &I : *TBB) {
  4169. PHINode *PN = dyn_cast<PHINode>(&I);
  4170. if (!PN)
  4171. break;
  4172. int i;
  4173. while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
  4174. PN->setIncomingBlock(i, TmpBB);
  4175. }
  4176. // Add another incoming edge form the new BB.
  4177. for (auto &I : *FBB) {
  4178. PHINode *PN = dyn_cast<PHINode>(&I);
  4179. if (!PN)
  4180. break;
  4181. auto *Val = PN->getIncomingValueForBlock(&BB);
  4182. PN->addIncoming(Val, TmpBB);
  4183. }
  4184. // Update the branch weights (from SelectionDAGBuilder::
  4185. // FindMergedConditions).
  4186. if (Opc == Instruction::Or) {
  4187. // Codegen X | Y as:
  4188. // BB1:
  4189. // jmp_if_X TBB
  4190. // jmp TmpBB
  4191. // TmpBB:
  4192. // jmp_if_Y TBB
  4193. // jmp FBB
  4194. //
  4195. // We have flexibility in setting Prob for BB1 and Prob for NewBB.
  4196. // The requirement is that
  4197. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  4198. // = TrueProb for orignal BB.
  4199. // Assuming the orignal weights are A and B, one choice is to set BB1's
  4200. // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
  4201. // assumes that
  4202. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  4203. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  4204. // TmpBB, but the math is more complicated.
  4205. uint64_t TrueWeight, FalseWeight;
  4206. if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
  4207. uint64_t NewTrueWeight = TrueWeight;
  4208. uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
  4209. scaleWeights(NewTrueWeight, NewFalseWeight);
  4210. Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
  4211. .createBranchWeights(TrueWeight, FalseWeight));
  4212. NewTrueWeight = TrueWeight;
  4213. NewFalseWeight = 2 * FalseWeight;
  4214. scaleWeights(NewTrueWeight, NewFalseWeight);
  4215. Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
  4216. .createBranchWeights(TrueWeight, FalseWeight));
  4217. }
  4218. } else {
  4219. // Codegen X & Y as:
  4220. // BB1:
  4221. // jmp_if_X TmpBB
  4222. // jmp FBB
  4223. // TmpBB:
  4224. // jmp_if_Y TBB
  4225. // jmp FBB
  4226. //
  4227. // This requires creation of TmpBB after CurBB.
  4228. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  4229. // The requirement is that
  4230. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  4231. // = FalseProb for orignal BB.
  4232. // Assuming the orignal weights are A and B, one choice is to set BB1's
  4233. // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
  4234. // assumes that
  4235. // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
  4236. uint64_t TrueWeight, FalseWeight;
  4237. if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
  4238. uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
  4239. uint64_t NewFalseWeight = FalseWeight;
  4240. scaleWeights(NewTrueWeight, NewFalseWeight);
  4241. Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
  4242. .createBranchWeights(TrueWeight, FalseWeight));
  4243. NewTrueWeight = 2 * TrueWeight;
  4244. NewFalseWeight = FalseWeight;
  4245. scaleWeights(NewTrueWeight, NewFalseWeight);
  4246. Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
  4247. .createBranchWeights(TrueWeight, FalseWeight));
  4248. }
  4249. }
  4250. // Note: No point in getting fancy here, since the DT info is never
  4251. // available to CodeGenPrepare.
  4252. ModifiedDT = true;
  4253. MadeChange = true;
  4254. DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
  4255. TmpBB->dump());
  4256. }
  4257. return MadeChange;
  4258. }