SROA.cpp 179 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616
  1. //===- SROA.cpp - Scalar Replacement Of Aggregates ------------------------===//
  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. /// \file
  10. /// This transformation implements the well known scalar replacement of
  11. /// aggregates transformation. It tries to identify promotable elements of an
  12. /// aggregate alloca, and promote them to registers. It will also try to
  13. /// convert uses of an element (or set of elements) of an alloca into a vector
  14. /// or bitfield-style integer scalar if appropriate.
  15. ///
  16. /// It works to do this with minimal slicing of the alloca so that regions
  17. /// which are merely transferred in and out of external memory remain unchanged
  18. /// and are not decomposed to scalar code.
  19. ///
  20. /// Because this also performs alloca promotion, it can be thought of as also
  21. /// serving the purpose of SSA formation. The algorithm iterates on the
  22. /// function until all opportunities for promotion have been realized.
  23. ///
  24. //===----------------------------------------------------------------------===//
  25. #include "llvm/Transforms/Scalar.h"
  26. #include "llvm/ADT/STLExtras.h"
  27. #include "llvm/ADT/SetVector.h"
  28. #include "llvm/ADT/SmallVector.h"
  29. #include "llvm/ADT/Statistic.h"
  30. #include "llvm/Analysis/AssumptionCache.h"
  31. #include "llvm/Analysis/Loads.h"
  32. #include "llvm/Analysis/PtrUseVisitor.h"
  33. #include "llvm/Analysis/ValueTracking.h"
  34. #include "llvm/IR/Constants.h"
  35. #include "llvm/IR/DIBuilder.h"
  36. #include "llvm/IR/DataLayout.h"
  37. #include "llvm/IR/DebugInfo.h"
  38. #include "llvm/IR/DerivedTypes.h"
  39. #include "llvm/IR/Dominators.h"
  40. #include "llvm/IR/Function.h"
  41. #include "llvm/IR/IRBuilder.h"
  42. #include "llvm/IR/InstVisitor.h"
  43. #include "llvm/IR/Instructions.h"
  44. #include "llvm/IR/IntrinsicInst.h"
  45. #include "llvm/IR/LLVMContext.h"
  46. #include "llvm/IR/Operator.h"
  47. #include "llvm/Pass.h"
  48. #include "llvm/Support/CommandLine.h"
  49. #include "llvm/Support/Compiler.h"
  50. #include "llvm/Support/Debug.h"
  51. #include "llvm/Support/ErrorHandling.h"
  52. #include "llvm/Support/MathExtras.h"
  53. #include "llvm/Support/TimeValue.h"
  54. #include "llvm/Support/raw_ostream.h"
  55. #include "llvm/Transforms/Utils/Local.h"
  56. #include "llvm/Transforms/Utils/PromoteMemToReg.h"
  57. #include "llvm/Transforms/Utils/SSAUpdater.h"
  58. #include "dxc/DXIL/DxilUtil.h" // HLSL Change - not sroa resource type.
  59. #if __cplusplus >= 201103L && !defined(NDEBUG)
  60. // We only use this for a debug check in C++11
  61. #include <random>
  62. #endif
  63. using namespace llvm;
  64. #define DEBUG_TYPE "sroa"
  65. STATISTIC(NumAllocasAnalyzed, "Number of allocas analyzed for replacement");
  66. STATISTIC(NumAllocaPartitions, "Number of alloca partitions formed");
  67. STATISTIC(MaxPartitionsPerAlloca, "Maximum number of partitions per alloca");
  68. STATISTIC(NumAllocaPartitionUses, "Number of alloca partition uses rewritten");
  69. STATISTIC(MaxUsesPerAllocaPartition, "Maximum number of uses of a partition");
  70. STATISTIC(NumNewAllocas, "Number of new, smaller allocas introduced");
  71. STATISTIC(NumPromoted, "Number of allocas promoted to SSA values");
  72. STATISTIC(NumLoadsSpeculated, "Number of loads speculated to allow promotion");
  73. STATISTIC(NumDeleted, "Number of instructions deleted");
  74. STATISTIC(NumVectorized, "Number of vectorized aggregates");
  75. #if 0 // HLSL Change Starts - option pending
  76. /// Hidden option to force the pass to not use DomTree and mem2reg, instead
  77. /// forming SSA values through the SSAUpdater infrastructure.
  78. static cl::opt<bool> ForceSSAUpdater("force-ssa-updater", cl::init(false),
  79. cl::Hidden);
  80. /// Hidden option to enable randomly shuffling the slices to help uncover
  81. /// instability in their order.
  82. static cl::opt<bool> SROARandomShuffleSlices("sroa-random-shuffle-slices",
  83. cl::init(false), cl::Hidden);
  84. /// Hidden option to experiment with completely strict handling of inbounds
  85. /// GEPs.
  86. static cl::opt<bool> SROAStrictInbounds("sroa-strict-inbounds", cl::init(false),
  87. cl::Hidden);
  88. #else
  89. static const bool ForceSSAUpdater = false;
  90. static const bool SROAStrictInbounds = false;
  91. #endif // HLSL Change Ends
  92. namespace {
  93. /// \brief A custom IRBuilder inserter which prefixes all names if they are
  94. /// preserved.
  95. template <bool preserveNames = true>
  96. class IRBuilderPrefixedInserter
  97. : public IRBuilderDefaultInserter<preserveNames> {
  98. std::string Prefix;
  99. public:
  100. void SetNamePrefix(const Twine &P) { Prefix = P.str(); }
  101. protected:
  102. void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
  103. BasicBlock::iterator InsertPt) const {
  104. IRBuilderDefaultInserter<preserveNames>::InsertHelper(
  105. I, Name.isTriviallyEmpty() ? Name : Prefix + Name, BB, InsertPt);
  106. }
  107. };
  108. // Specialization for not preserving the name is trivial.
  109. template <>
  110. class IRBuilderPrefixedInserter<false>
  111. : public IRBuilderDefaultInserter<false> {
  112. public:
  113. void SetNamePrefix(const Twine &P) {}
  114. };
  115. /// \brief Provide a typedef for IRBuilder that drops names in release builds.
  116. #ifndef NDEBUG
  117. typedef llvm::IRBuilder<true, ConstantFolder, IRBuilderPrefixedInserter<true>>
  118. IRBuilderTy;
  119. #else
  120. typedef llvm::IRBuilder<false, ConstantFolder, IRBuilderPrefixedInserter<false>>
  121. IRBuilderTy;
  122. #endif
  123. }
  124. namespace {
  125. /// \brief A used slice of an alloca.
  126. ///
  127. /// This structure represents a slice of an alloca used by some instruction. It
  128. /// stores both the begin and end offsets of this use, a pointer to the use
  129. /// itself, and a flag indicating whether we can classify the use as splittable
  130. /// or not when forming partitions of the alloca.
  131. class Slice {
  132. /// \brief The beginning offset of the range.
  133. uint64_t BeginOffset;
  134. /// \brief The ending offset, not included in the range.
  135. uint64_t EndOffset;
  136. /// \brief Storage for both the use of this slice and whether it can be
  137. /// split.
  138. PointerIntPair<Use *, 1, bool> UseAndIsSplittable;
  139. public:
  140. Slice() : BeginOffset(), EndOffset() {}
  141. Slice(uint64_t BeginOffset, uint64_t EndOffset, Use *U, bool IsSplittable)
  142. : BeginOffset(BeginOffset), EndOffset(EndOffset),
  143. UseAndIsSplittable(U, IsSplittable) {}
  144. uint64_t beginOffset() const { return BeginOffset; }
  145. uint64_t endOffset() const { return EndOffset; }
  146. bool isSplittable() const { return UseAndIsSplittable.getInt(); }
  147. void makeUnsplittable() { UseAndIsSplittable.setInt(false); }
  148. Use *getUse() const { return UseAndIsSplittable.getPointer(); }
  149. bool isDead() const { return getUse() == nullptr; }
  150. void kill() { UseAndIsSplittable.setPointer(nullptr); }
  151. /// \brief Support for ordering ranges.
  152. ///
  153. /// This provides an ordering over ranges such that start offsets are
  154. /// always increasing, and within equal start offsets, the end offsets are
  155. /// decreasing. Thus the spanning range comes first in a cluster with the
  156. /// same start position.
  157. bool operator<(const Slice &RHS) const {
  158. if (beginOffset() < RHS.beginOffset())
  159. return true;
  160. if (beginOffset() > RHS.beginOffset())
  161. return false;
  162. if (isSplittable() != RHS.isSplittable())
  163. return !isSplittable();
  164. if (endOffset() > RHS.endOffset())
  165. return true;
  166. return false;
  167. }
  168. /// \brief Support comparison with a single offset to allow binary searches.
  169. friend LLVM_ATTRIBUTE_UNUSED bool operator<(const Slice &LHS,
  170. uint64_t RHSOffset) {
  171. return LHS.beginOffset() < RHSOffset;
  172. }
  173. friend LLVM_ATTRIBUTE_UNUSED bool operator<(uint64_t LHSOffset,
  174. const Slice &RHS) {
  175. return LHSOffset < RHS.beginOffset();
  176. }
  177. bool operator==(const Slice &RHS) const {
  178. return isSplittable() == RHS.isSplittable() &&
  179. beginOffset() == RHS.beginOffset() && endOffset() == RHS.endOffset();
  180. }
  181. bool operator!=(const Slice &RHS) const { return !operator==(RHS); }
  182. };
  183. } // end anonymous namespace
  184. namespace llvm {
  185. template <typename T> struct isPodLike;
  186. template <> struct isPodLike<Slice> { static const bool value = true; };
  187. }
  188. namespace {
  189. /// \brief Representation of the alloca slices.
  190. ///
  191. /// This class represents the slices of an alloca which are formed by its
  192. /// various uses. If a pointer escapes, we can't fully build a representation
  193. /// for the slices used and we reflect that in this structure. The uses are
  194. /// stored, sorted by increasing beginning offset and with unsplittable slices
  195. /// starting at a particular offset before splittable slices.
  196. class AllocaSlices {
  197. public:
  198. /// \brief Construct the slices of a particular alloca.
  199. AllocaSlices(const DataLayout &DL, AllocaInst &AI,
  200. const bool SkipHLSLMat); // HLSL Change - not sroa matrix type.
  201. /// \brief Test whether a pointer to the allocation escapes our analysis.
  202. ///
  203. /// If this is true, the slices are never fully built and should be
  204. /// ignored.
  205. bool isEscaped() const { return PointerEscapingInstr; }
  206. /// \brief Support for iterating over the slices.
  207. /// @{
  208. typedef SmallVectorImpl<Slice>::iterator iterator;
  209. typedef iterator_range<iterator> range;
  210. iterator begin() { return Slices.begin(); }
  211. iterator end() { return Slices.end(); }
  212. typedef SmallVectorImpl<Slice>::const_iterator const_iterator;
  213. typedef iterator_range<const_iterator> const_range;
  214. const_iterator begin() const { return Slices.begin(); }
  215. const_iterator end() const { return Slices.end(); }
  216. /// @}
  217. /// \brief Erase a range of slices.
  218. void erase(iterator Start, iterator Stop) { Slices.erase(Start, Stop); }
  219. /// \brief Insert new slices for this alloca.
  220. ///
  221. /// This moves the slices into the alloca's slices collection, and re-sorts
  222. /// everything so that the usual ordering properties of the alloca's slices
  223. /// hold.
  224. void insert(ArrayRef<Slice> NewSlices) {
  225. int OldSize = Slices.size();
  226. Slices.append(NewSlices.begin(), NewSlices.end());
  227. auto SliceI = Slices.begin() + OldSize;
  228. std::sort(SliceI, Slices.end());
  229. std::inplace_merge(Slices.begin(), SliceI, Slices.end());
  230. }
  231. // Forward declare an iterator to befriend it.
  232. class partition_iterator;
  233. /// \brief A partition of the slices.
  234. ///
  235. /// An ephemeral representation for a range of slices which can be viewed as
  236. /// a partition of the alloca. This range represents a span of the alloca's
  237. /// memory which cannot be split, and provides access to all of the slices
  238. /// overlapping some part of the partition.
  239. ///
  240. /// Objects of this type are produced by traversing the alloca's slices, but
  241. /// are only ephemeral and not persistent.
  242. class Partition {
  243. private:
  244. friend class AllocaSlices;
  245. friend class AllocaSlices::partition_iterator;
  246. /// \brief The begining and ending offsets of the alloca for this partition.
  247. uint64_t BeginOffset, EndOffset;
  248. /// \brief The start end end iterators of this partition.
  249. iterator SI, SJ;
  250. /// \brief A collection of split slice tails overlapping the partition.
  251. SmallVector<Slice *, 4> SplitTails;
  252. /// \brief Raw constructor builds an empty partition starting and ending at
  253. /// the given iterator.
  254. Partition(iterator SI) : SI(SI), SJ(SI) {}
  255. public:
  256. /// \brief The start offset of this partition.
  257. ///
  258. /// All of the contained slices start at or after this offset.
  259. uint64_t beginOffset() const { return BeginOffset; }
  260. /// \brief The end offset of this partition.
  261. ///
  262. /// All of the contained slices end at or before this offset.
  263. uint64_t endOffset() const { return EndOffset; }
  264. /// \brief The size of the partition.
  265. ///
  266. /// Note that this can never be zero.
  267. uint64_t size() const {
  268. assert(BeginOffset < EndOffset && "Partitions must span some bytes!");
  269. return EndOffset - BeginOffset;
  270. }
  271. /// \brief Test whether this partition contains no slices, and merely spans
  272. /// a region occupied by split slices.
  273. bool empty() const { return SI == SJ; }
  274. /// \name Iterate slices that start within the partition.
  275. /// These may be splittable or unsplittable. They have a begin offset >= the
  276. /// partition begin offset.
  277. /// @{
  278. // FIXME: We should probably define a "concat_iterator" helper and use that
  279. // to stitch together pointee_iterators over the split tails and the
  280. // contiguous iterators of the partition. That would give a much nicer
  281. // interface here. We could then additionally expose filtered iterators for
  282. // split, unsplit, and unsplittable splices based on the usage patterns.
  283. iterator begin() const { return SI; }
  284. iterator end() const { return SJ; }
  285. /// @}
  286. /// \brief Get the sequence of split slice tails.
  287. ///
  288. /// These tails are of slices which start before this partition but are
  289. /// split and overlap into the partition. We accumulate these while forming
  290. /// partitions.
  291. ArrayRef<Slice *> splitSliceTails() const { return SplitTails; }
  292. };
  293. /// \brief An iterator over partitions of the alloca's slices.
  294. ///
  295. /// This iterator implements the core algorithm for partitioning the alloca's
  296. /// slices. It is a forward iterator as we don't support backtracking for
  297. /// efficiency reasons, and re-use a single storage area to maintain the
  298. /// current set of split slices.
  299. ///
  300. /// It is templated on the slice iterator type to use so that it can operate
  301. /// with either const or non-const slice iterators.
  302. class partition_iterator
  303. : public iterator_facade_base<partition_iterator,
  304. std::forward_iterator_tag, Partition> {
  305. friend class AllocaSlices;
  306. /// \brief Most of the state for walking the partitions is held in a class
  307. /// with a nice interface for examining them.
  308. Partition P;
  309. /// \brief We need to keep the end of the slices to know when to stop.
  310. AllocaSlices::iterator SE;
  311. /// \brief We also need to keep track of the maximum split end offset seen.
  312. /// FIXME: Do we really?
  313. uint64_t MaxSplitSliceEndOffset;
  314. /// \brief Sets the partition to be empty at given iterator, and sets the
  315. /// end iterator.
  316. partition_iterator(AllocaSlices::iterator SI, AllocaSlices::iterator SE)
  317. : P(SI), SE(SE), MaxSplitSliceEndOffset(0) {
  318. // If not already at the end, advance our state to form the initial
  319. // partition.
  320. if (SI != SE)
  321. advance();
  322. }
  323. /// \brief Advance the iterator to the next partition.
  324. ///
  325. /// Requires that the iterator not be at the end of the slices.
  326. void advance() {
  327. assert((P.SI != SE || !P.SplitTails.empty()) &&
  328. "Cannot advance past the end of the slices!");
  329. // Clear out any split uses which have ended.
  330. if (!P.SplitTails.empty()) {
  331. if (P.EndOffset >= MaxSplitSliceEndOffset) {
  332. // If we've finished all splits, this is easy.
  333. P.SplitTails.clear();
  334. MaxSplitSliceEndOffset = 0;
  335. } else {
  336. // Remove the uses which have ended in the prior partition. This
  337. // cannot change the max split slice end because we just checked that
  338. // the prior partition ended prior to that max.
  339. P.SplitTails.erase(
  340. std::remove_if(
  341. P.SplitTails.begin(), P.SplitTails.end(),
  342. [&](Slice *S) { return S->endOffset() <= P.EndOffset; }),
  343. P.SplitTails.end());
  344. assert(std::any_of(P.SplitTails.begin(), P.SplitTails.end(),
  345. [&](Slice *S) {
  346. return S->endOffset() == MaxSplitSliceEndOffset;
  347. }) &&
  348. "Could not find the current max split slice offset!");
  349. assert(std::all_of(P.SplitTails.begin(), P.SplitTails.end(),
  350. [&](Slice *S) {
  351. return S->endOffset() <= MaxSplitSliceEndOffset;
  352. }) &&
  353. "Max split slice end offset is not actually the max!");
  354. }
  355. }
  356. // If P.SI is already at the end, then we've cleared the split tail and
  357. // now have an end iterator.
  358. if (P.SI == SE) {
  359. assert(P.SplitTails.empty() && "Failed to clear the split slices!");
  360. return;
  361. }
  362. // If we had a non-empty partition previously, set up the state for
  363. // subsequent partitions.
  364. if (P.SI != P.SJ) {
  365. // Accumulate all the splittable slices which started in the old
  366. // partition into the split list.
  367. for (Slice &S : P)
  368. if (S.isSplittable() && S.endOffset() > P.EndOffset) {
  369. P.SplitTails.push_back(&S);
  370. MaxSplitSliceEndOffset =
  371. std::max(S.endOffset(), MaxSplitSliceEndOffset);
  372. }
  373. // Start from the end of the previous partition.
  374. P.SI = P.SJ;
  375. // If P.SI is now at the end, we at most have a tail of split slices.
  376. if (P.SI == SE) {
  377. P.BeginOffset = P.EndOffset;
  378. P.EndOffset = MaxSplitSliceEndOffset;
  379. return;
  380. }
  381. // If the we have split slices and the next slice is after a gap and is
  382. // not splittable immediately form an empty partition for the split
  383. // slices up until the next slice begins.
  384. if (!P.SplitTails.empty() && P.SI->beginOffset() != P.EndOffset &&
  385. !P.SI->isSplittable()) {
  386. P.BeginOffset = P.EndOffset;
  387. P.EndOffset = P.SI->beginOffset();
  388. return;
  389. }
  390. }
  391. // OK, we need to consume new slices. Set the end offset based on the
  392. // current slice, and step SJ past it. The beginning offset of the
  393. // parttion is the beginning offset of the next slice unless we have
  394. // pre-existing split slices that are continuing, in which case we begin
  395. // at the prior end offset.
  396. P.BeginOffset = P.SplitTails.empty() ? P.SI->beginOffset() : P.EndOffset;
  397. P.EndOffset = P.SI->endOffset();
  398. ++P.SJ;
  399. // There are two strategies to form a partition based on whether the
  400. // partition starts with an unsplittable slice or a splittable slice.
  401. if (!P.SI->isSplittable()) {
  402. // When we're forming an unsplittable region, it must always start at
  403. // the first slice and will extend through its end.
  404. assert(P.BeginOffset == P.SI->beginOffset());
  405. // Form a partition including all of the overlapping slices with this
  406. // unsplittable slice.
  407. while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
  408. if (!P.SJ->isSplittable())
  409. P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
  410. ++P.SJ;
  411. }
  412. // We have a partition across a set of overlapping unsplittable
  413. // partitions.
  414. return;
  415. }
  416. // If we're starting with a splittable slice, then we need to form
  417. // a synthetic partition spanning it and any other overlapping splittable
  418. // splices.
  419. assert(P.SI->isSplittable() && "Forming a splittable partition!");
  420. // Collect all of the overlapping splittable slices.
  421. while (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset &&
  422. P.SJ->isSplittable()) {
  423. P.EndOffset = std::max(P.EndOffset, P.SJ->endOffset());
  424. ++P.SJ;
  425. }
  426. // Back upiP.EndOffset if we ended the span early when encountering an
  427. // unsplittable slice. This synthesizes the early end offset of
  428. // a partition spanning only splittable slices.
  429. if (P.SJ != SE && P.SJ->beginOffset() < P.EndOffset) {
  430. assert(!P.SJ->isSplittable());
  431. P.EndOffset = P.SJ->beginOffset();
  432. }
  433. }
  434. public:
  435. bool operator==(const partition_iterator &RHS) const {
  436. assert(SE == RHS.SE &&
  437. "End iterators don't match between compared partition iterators!");
  438. // The observed positions of partitions is marked by the P.SI iterator and
  439. // the emptyness of the split slices. The latter is only relevant when
  440. // P.SI == SE, as the end iterator will additionally have an empty split
  441. // slices list, but the prior may have the same P.SI and a tail of split
  442. // slices.
  443. if (P.SI == RHS.P.SI &&
  444. P.SplitTails.empty() == RHS.P.SplitTails.empty()) {
  445. assert(P.SJ == RHS.P.SJ &&
  446. "Same set of slices formed two different sized partitions!");
  447. assert(P.SplitTails.size() == RHS.P.SplitTails.size() &&
  448. "Same slice position with differently sized non-empty split "
  449. "slice tails!");
  450. return true;
  451. }
  452. return false;
  453. }
  454. partition_iterator &operator++() {
  455. advance();
  456. return *this;
  457. }
  458. Partition &operator*() { return P; }
  459. };
  460. /// \brief A forward range over the partitions of the alloca's slices.
  461. ///
  462. /// This accesses an iterator range over the partitions of the alloca's
  463. /// slices. It computes these partitions on the fly based on the overlapping
  464. /// offsets of the slices and the ability to split them. It will visit "empty"
  465. /// partitions to cover regions of the alloca only accessed via split
  466. /// slices.
  467. iterator_range<partition_iterator> partitions() {
  468. return make_range(partition_iterator(begin(), end()),
  469. partition_iterator(end(), end()));
  470. }
  471. /// \brief Access the dead users for this alloca.
  472. ArrayRef<Instruction *> getDeadUsers() const { return DeadUsers; }
  473. /// \brief Access the dead operands referring to this alloca.
  474. ///
  475. /// These are operands which have cannot actually be used to refer to the
  476. /// alloca as they are outside its range and the user doesn't correct for
  477. /// that. These mostly consist of PHI node inputs and the like which we just
  478. /// need to replace with undef.
  479. ArrayRef<Use *> getDeadOperands() const { return DeadOperands; }
  480. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  481. void print(raw_ostream &OS, const_iterator I, StringRef Indent = " ") const;
  482. void printSlice(raw_ostream &OS, const_iterator I,
  483. StringRef Indent = " ") const;
  484. void printUse(raw_ostream &OS, const_iterator I,
  485. StringRef Indent = " ") const;
  486. void print(raw_ostream &OS) const;
  487. void dump(const_iterator I) const;
  488. void dump() const;
  489. #endif
  490. private:
  491. template <typename DerivedT, typename RetT = void> class BuilderBase;
  492. class SliceBuilder;
  493. friend class AllocaSlices::SliceBuilder;
  494. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  495. /// \brief Handle to alloca instruction to simplify method interfaces.
  496. AllocaInst &AI;
  497. #endif
  498. /// \brief The instruction responsible for this alloca not having a known set
  499. /// of slices.
  500. ///
  501. /// When an instruction (potentially) escapes the pointer to the alloca, we
  502. /// store a pointer to that here and abort trying to form slices of the
  503. /// alloca. This will be null if the alloca slices are analyzed successfully.
  504. Instruction *PointerEscapingInstr;
  505. /// \brief The slices of the alloca.
  506. ///
  507. /// We store a vector of the slices formed by uses of the alloca here. This
  508. /// vector is sorted by increasing begin offset, and then the unsplittable
  509. /// slices before the splittable ones. See the Slice inner class for more
  510. /// details.
  511. SmallVector<Slice, 8> Slices;
  512. /// \brief Instructions which will become dead if we rewrite the alloca.
  513. ///
  514. /// Note that these are not separated by slice. This is because we expect an
  515. /// alloca to be completely rewritten or not rewritten at all. If rewritten,
  516. /// all these instructions can simply be removed and replaced with undef as
  517. /// they come from outside of the allocated space.
  518. SmallVector<Instruction *, 8> DeadUsers;
  519. /// \brief Operands which will become dead if we rewrite the alloca.
  520. ///
  521. /// These are operands that in their particular use can be replaced with
  522. /// undef when we rewrite the alloca. These show up in out-of-bounds inputs
  523. /// to PHI nodes and the like. They aren't entirely dead (there might be
  524. /// a GEP back into the bounds using it elsewhere) and nor is the PHI, but we
  525. /// want to swap this particular input for undef to simplify the use lists of
  526. /// the alloca.
  527. SmallVector<Use *, 8> DeadOperands;
  528. };
  529. }
  530. static Value *foldSelectInst(SelectInst &SI) {
  531. // If the condition being selected on is a constant or the same value is
  532. // being selected between, fold the select. Yes this does (rarely) happen
  533. // early on.
  534. if (ConstantInt *CI = dyn_cast<ConstantInt>(SI.getCondition()))
  535. return SI.getOperand(1 + CI->isZero());
  536. if (SI.getOperand(1) == SI.getOperand(2))
  537. return SI.getOperand(1);
  538. return nullptr;
  539. }
  540. /// \brief A helper that folds a PHI node or a select.
  541. static Value *foldPHINodeOrSelectInst(Instruction &I) {
  542. if (PHINode *PN = dyn_cast<PHINode>(&I)) {
  543. // If PN merges together the same value, return that value.
  544. return PN->hasConstantValue();
  545. }
  546. return foldSelectInst(cast<SelectInst>(I));
  547. }
  548. /// \brief Builder for the alloca slices.
  549. ///
  550. /// This class builds a set of alloca slices by recursively visiting the uses
  551. /// of an alloca and making a slice for each load and store at each offset.
  552. class AllocaSlices::SliceBuilder : public PtrUseVisitor<SliceBuilder> {
  553. friend class PtrUseVisitor<SliceBuilder>;
  554. friend class InstVisitor<SliceBuilder>;
  555. typedef PtrUseVisitor<SliceBuilder> Base;
  556. const bool SkipHLSLMat; // HLSL Change - not sroa matrix type.
  557. const uint64_t AllocSize;
  558. AllocaSlices &AS;
  559. SmallDenseMap<Instruction *, unsigned> MemTransferSliceMap;
  560. SmallDenseMap<Instruction *, uint64_t> PHIOrSelectSizes;
  561. /// \brief Set to de-duplicate dead instructions found in the use walk.
  562. SmallPtrSet<Instruction *, 4> VisitedDeadInsts;
  563. public:
  564. SliceBuilder(const DataLayout &DL, AllocaInst &AI, AllocaSlices &AS,
  565. const bool SkipHLSLMat)
  566. : PtrUseVisitor<SliceBuilder>(DL),
  567. SkipHLSLMat(SkipHLSLMat), // HLSL Change - not sroa matrix type.
  568. AllocSize(DL.getTypeAllocSize(AI.getAllocatedType())), AS(AS) {}
  569. private:
  570. void markAsDead(Instruction &I) {
  571. if (VisitedDeadInsts.insert(&I).second)
  572. AS.DeadUsers.push_back(&I);
  573. }
  574. void insertUse(Instruction &I, const APInt &Offset, uint64_t Size,
  575. bool IsSplittable = false) {
  576. // Completely skip uses which have a zero size or start either before or
  577. // past the end of the allocation.
  578. if (Size == 0 || Offset.uge(AllocSize)) {
  579. DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte use @" << Offset
  580. << " which has zero size or starts outside of the "
  581. << AllocSize << " byte alloca:\n"
  582. << " alloca: " << AS.AI << "\n"
  583. << " use: " << I << "\n");
  584. return markAsDead(I);
  585. }
  586. uint64_t BeginOffset = Offset.getZExtValue();
  587. uint64_t EndOffset = BeginOffset + Size;
  588. // Clamp the end offset to the end of the allocation. Note that this is
  589. // formulated to handle even the case where "BeginOffset + Size" overflows.
  590. // This may appear superficially to be something we could ignore entirely,
  591. // but that is not so! There may be widened loads or PHI-node uses where
  592. // some instructions are dead but not others. We can't completely ignore
  593. // them, and so have to record at least the information here.
  594. assert(AllocSize >= BeginOffset); // Established above.
  595. if (Size > AllocSize - BeginOffset) {
  596. DEBUG(dbgs() << "WARNING: Clamping a " << Size << " byte use @" << Offset
  597. << " to remain within the " << AllocSize << " byte alloca:\n"
  598. << " alloca: " << AS.AI << "\n"
  599. << " use: " << I << "\n");
  600. EndOffset = AllocSize;
  601. }
  602. AS.Slices.push_back(Slice(BeginOffset, EndOffset, U, IsSplittable));
  603. }
  604. void visitBitCastInst(BitCastInst &BC) {
  605. if (BC.use_empty())
  606. return markAsDead(BC);
  607. // HLSL Change Begin - not sroa matrix type.
  608. if (PointerType *PT = dyn_cast<PointerType>(BC.getType())) {
  609. Type *EltTy = PT->getElementType();
  610. if ((SkipHLSLMat && hlsl::dxilutil::IsHLSLMatrixType(EltTy)) ||
  611. hlsl::dxilutil::IsHLSLObjectType(EltTy)) {
  612. AS.PointerEscapingInstr = &BC;
  613. return;
  614. }
  615. if (PointerType *SrcPT = dyn_cast<PointerType>(BC.getSrcTy())) {
  616. Type *SrcEltTy = SrcPT->getElementType();
  617. if ((SkipHLSLMat && hlsl::dxilutil::IsHLSLMatrixType(SrcEltTy)) ||
  618. hlsl::dxilutil::IsHLSLObjectType(SrcEltTy)) {
  619. AS.PointerEscapingInstr = &BC;
  620. return;
  621. }
  622. }
  623. }
  624. // HLSL Change End.
  625. return Base::visitBitCastInst(BC);
  626. }
  627. void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
  628. if (GEPI.use_empty())
  629. return markAsDead(GEPI);
  630. if (SROAStrictInbounds && GEPI.isInBounds()) {
  631. // FIXME: This is a manually un-factored variant of the basic code inside
  632. // of GEPs with checking of the inbounds invariant specified in the
  633. // langref in a very strict sense. If we ever want to enable
  634. // SROAStrictInbounds, this code should be factored cleanly into
  635. // PtrUseVisitor, but it is easier to experiment with SROAStrictInbounds
  636. // by writing out the code here where we have tho underlying allocation
  637. // size readily available.
  638. APInt GEPOffset = Offset;
  639. const DataLayout &DL = GEPI.getModule()->getDataLayout();
  640. for (gep_type_iterator GTI = gep_type_begin(GEPI),
  641. GTE = gep_type_end(GEPI);
  642. GTI != GTE; ++GTI) {
  643. ConstantInt *OpC = dyn_cast<ConstantInt>(GTI.getOperand());
  644. if (!OpC)
  645. break;
  646. // Handle a struct index, which adds its field offset to the pointer.
  647. if (StructType *STy = dyn_cast<StructType>(*GTI)) {
  648. unsigned ElementIdx = OpC->getZExtValue();
  649. const StructLayout *SL = DL.getStructLayout(STy);
  650. GEPOffset +=
  651. APInt(Offset.getBitWidth(), SL->getElementOffset(ElementIdx));
  652. } else {
  653. // For array or vector indices, scale the index by the size of the
  654. // type.
  655. APInt Index = OpC->getValue().sextOrTrunc(Offset.getBitWidth());
  656. GEPOffset += Index * APInt(Offset.getBitWidth(),
  657. DL.getTypeAllocSize(GTI.getIndexedType()));
  658. }
  659. // If this index has computed an intermediate pointer which is not
  660. // inbounds, then the result of the GEP is a poison value and we can
  661. // delete it and all uses.
  662. if (GEPOffset.ugt(AllocSize))
  663. return markAsDead(GEPI);
  664. }
  665. }
  666. return Base::visitGetElementPtrInst(GEPI);
  667. }
  668. void handleLoadOrStore(Type *Ty, Instruction &I, const APInt &Offset,
  669. uint64_t Size, bool IsVolatile) {
  670. // We allow splitting of non-volatile loads and stores where the type is an
  671. // integer type. These may be used to implement 'memcpy' or other "transfer
  672. // of bits" patterns.
  673. bool IsSplittable = Ty->isIntegerTy() && !IsVolatile;
  674. insertUse(I, Offset, Size, IsSplittable);
  675. }
  676. void visitLoadInst(LoadInst &LI) {
  677. // HLSL Change Begin - not sroa matrix type.
  678. if ((SkipHLSLMat && hlsl::dxilutil::IsHLSLMatrixType(LI.getType())) ||
  679. hlsl::dxilutil::IsHLSLObjectType(LI.getType()))
  680. return PI.setEscapedAndAborted(&LI);
  681. // HLSL Change End.
  682. assert((!LI.isSimple() || LI.getType()->isSingleValueType()) &&
  683. "All simple FCA loads should have been pre-split");
  684. if (!IsOffsetKnown)
  685. return PI.setAborted(&LI);
  686. const DataLayout &DL = LI.getModule()->getDataLayout();
  687. uint64_t Size = DL.getTypeStoreSize(LI.getType());
  688. return handleLoadOrStore(LI.getType(), LI, Offset, Size, LI.isVolatile());
  689. }
  690. void visitStoreInst(StoreInst &SI) {
  691. Value *ValOp = SI.getValueOperand();
  692. if (ValOp == *U)
  693. return PI.setEscapedAndAborted(&SI);
  694. // HLSL Change Begin - not sroa matrix type.
  695. if ((SkipHLSLMat && hlsl::dxilutil::IsHLSLMatrixType(ValOp->getType())) ||
  696. hlsl::dxilutil::IsHLSLObjectType(ValOp->getType()))
  697. return PI.setEscapedAndAborted(&SI);
  698. // HLSL Change End.
  699. if (!IsOffsetKnown)
  700. return PI.setAborted(&SI);
  701. const DataLayout &DL = SI.getModule()->getDataLayout();
  702. uint64_t Size = DL.getTypeStoreSize(ValOp->getType());
  703. // If this memory access can be shown to *statically* extend outside the
  704. // bounds of of the allocation, it's behavior is undefined, so simply
  705. // ignore it. Note that this is more strict than the generic clamping
  706. // behavior of insertUse. We also try to handle cases which might run the
  707. // risk of overflow.
  708. // FIXME: We should instead consider the pointer to have escaped if this
  709. // function is being instrumented for addressing bugs or race conditions.
  710. if (Size > AllocSize || Offset.ugt(AllocSize - Size)) {
  711. DEBUG(dbgs() << "WARNING: Ignoring " << Size << " byte store @" << Offset
  712. << " which extends past the end of the " << AllocSize
  713. << " byte alloca:\n"
  714. << " alloca: " << AS.AI << "\n"
  715. << " use: " << SI << "\n");
  716. return markAsDead(SI);
  717. }
  718. assert((!SI.isSimple() || ValOp->getType()->isSingleValueType()) &&
  719. "All simple FCA stores should have been pre-split");
  720. handleLoadOrStore(ValOp->getType(), SI, Offset, Size, SI.isVolatile());
  721. }
  722. void visitMemSetInst(MemSetInst &II) {
  723. assert(II.getRawDest() == *U && "Pointer use is not the destination?");
  724. ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
  725. if ((Length && Length->getValue() == 0) ||
  726. (IsOffsetKnown && Offset.uge(AllocSize)))
  727. // Zero-length mem transfer intrinsics can be ignored entirely.
  728. return markAsDead(II);
  729. if (!IsOffsetKnown)
  730. return PI.setAborted(&II);
  731. insertUse(II, Offset, Length ? Length->getLimitedValue()
  732. : AllocSize - Offset.getLimitedValue(),
  733. (bool)Length);
  734. }
  735. void visitMemTransferInst(MemTransferInst &II) {
  736. ConstantInt *Length = dyn_cast<ConstantInt>(II.getLength());
  737. if (Length && Length->getValue() == 0)
  738. // Zero-length mem transfer intrinsics can be ignored entirely.
  739. return markAsDead(II);
  740. // Because we can visit these intrinsics twice, also check to see if the
  741. // first time marked this instruction as dead. If so, skip it.
  742. if (VisitedDeadInsts.count(&II))
  743. return;
  744. if (!IsOffsetKnown)
  745. return PI.setAborted(&II);
  746. // This side of the transfer is completely out-of-bounds, and so we can
  747. // nuke the entire transfer. However, we also need to nuke the other side
  748. // if already added to our partitions.
  749. // FIXME: Yet another place we really should bypass this when
  750. // instrumenting for ASan.
  751. if (Offset.uge(AllocSize)) {
  752. SmallDenseMap<Instruction *, unsigned>::iterator MTPI =
  753. MemTransferSliceMap.find(&II);
  754. if (MTPI != MemTransferSliceMap.end())
  755. AS.Slices[MTPI->second].kill();
  756. return markAsDead(II);
  757. }
  758. uint64_t RawOffset = Offset.getLimitedValue();
  759. uint64_t Size = Length ? Length->getLimitedValue() : AllocSize - RawOffset;
  760. // Check for the special case where the same exact value is used for both
  761. // source and dest.
  762. if (*U == II.getRawDest() && *U == II.getRawSource()) {
  763. // For non-volatile transfers this is a no-op.
  764. if (!II.isVolatile())
  765. return markAsDead(II);
  766. return insertUse(II, Offset, Size, /*IsSplittable=*/false);
  767. }
  768. // If we have seen both source and destination for a mem transfer, then
  769. // they both point to the same alloca.
  770. bool Inserted;
  771. SmallDenseMap<Instruction *, unsigned>::iterator MTPI;
  772. std::tie(MTPI, Inserted) =
  773. MemTransferSliceMap.insert(std::make_pair(&II, AS.Slices.size()));
  774. unsigned PrevIdx = MTPI->second;
  775. if (!Inserted) {
  776. Slice &PrevP = AS.Slices[PrevIdx];
  777. // Check if the begin offsets match and this is a non-volatile transfer.
  778. // In that case, we can completely elide the transfer.
  779. if (!II.isVolatile() && PrevP.beginOffset() == RawOffset) {
  780. PrevP.kill();
  781. return markAsDead(II);
  782. }
  783. // Otherwise we have an offset transfer within the same alloca. We can't
  784. // split those.
  785. PrevP.makeUnsplittable();
  786. }
  787. // Insert the use now that we've fixed up the splittable nature.
  788. insertUse(II, Offset, Size, /*IsSplittable=*/Inserted && Length);
  789. // Check that we ended up with a valid index in the map.
  790. assert(AS.Slices[PrevIdx].getUse()->getUser() == &II &&
  791. "Map index doesn't point back to a slice with this user.");
  792. }
  793. // Disable SRoA for any intrinsics except for lifetime invariants.
  794. // FIXME: What about debug intrinsics? This matches old behavior, but
  795. // doesn't make sense.
  796. void visitIntrinsicInst(IntrinsicInst &II) {
  797. if (!IsOffsetKnown)
  798. return PI.setAborted(&II);
  799. if (II.getIntrinsicID() == Intrinsic::lifetime_start ||
  800. II.getIntrinsicID() == Intrinsic::lifetime_end) {
  801. ConstantInt *Length = cast<ConstantInt>(II.getArgOperand(0));
  802. uint64_t Size = std::min(AllocSize - Offset.getLimitedValue(),
  803. Length->getLimitedValue());
  804. insertUse(II, Offset, Size, true);
  805. return;
  806. }
  807. Base::visitIntrinsicInst(II);
  808. }
  809. Instruction *hasUnsafePHIOrSelectUse(Instruction *Root, uint64_t &Size) {
  810. // We consider any PHI or select that results in a direct load or store of
  811. // the same offset to be a viable use for slicing purposes. These uses
  812. // are considered unsplittable and the size is the maximum loaded or stored
  813. // size.
  814. SmallPtrSet<Instruction *, 4> Visited;
  815. SmallVector<std::pair<Instruction *, Instruction *>, 4> Uses;
  816. Visited.insert(Root);
  817. Uses.push_back(std::make_pair(cast<Instruction>(*U), Root));
  818. const DataLayout &DL = Root->getModule()->getDataLayout();
  819. // If there are no loads or stores, the access is dead. We mark that as
  820. // a size zero access.
  821. Size = 0;
  822. do {
  823. Instruction *I, *UsedI;
  824. std::tie(UsedI, I) = Uses.pop_back_val();
  825. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  826. Size = std::max(Size, DL.getTypeStoreSize(LI->getType()));
  827. continue;
  828. }
  829. if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  830. Value *Op = SI->getOperand(0);
  831. if (Op == UsedI)
  832. return SI;
  833. Size = std::max(Size, DL.getTypeStoreSize(Op->getType()));
  834. continue;
  835. }
  836. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
  837. if (!GEP->hasAllZeroIndices())
  838. return GEP;
  839. } else if (!isa<BitCastInst>(I) && !isa<PHINode>(I) &&
  840. !isa<SelectInst>(I)) {
  841. return I;
  842. }
  843. for (User *U : I->users())
  844. if (Visited.insert(cast<Instruction>(U)).second)
  845. Uses.push_back(std::make_pair(I, cast<Instruction>(U)));
  846. } while (!Uses.empty());
  847. return nullptr;
  848. }
  849. void visitPHINodeOrSelectInst(Instruction &I) {
  850. assert(isa<PHINode>(I) || isa<SelectInst>(I));
  851. if (I.use_empty())
  852. return markAsDead(I);
  853. // TODO: We could use SimplifyInstruction here to fold PHINodes and
  854. // SelectInsts. However, doing so requires to change the current
  855. // dead-operand-tracking mechanism. For instance, suppose neither loading
  856. // from %U nor %other traps. Then "load (select undef, %U, %other)" does not
  857. // trap either. However, if we simply replace %U with undef using the
  858. // current dead-operand-tracking mechanism, "load (select undef, undef,
  859. // %other)" may trap because the select may return the first operand
  860. // "undef".
  861. if (Value *Result = foldPHINodeOrSelectInst(I)) {
  862. if (Result == *U)
  863. // If the result of the constant fold will be the pointer, recurse
  864. // through the PHI/select as if we had RAUW'ed it.
  865. enqueueUsers(I);
  866. else
  867. // Otherwise the operand to the PHI/select is dead, and we can replace
  868. // it with undef.
  869. AS.DeadOperands.push_back(U);
  870. return;
  871. }
  872. if (!IsOffsetKnown)
  873. return PI.setAborted(&I);
  874. // See if we already have computed info on this node.
  875. uint64_t &Size = PHIOrSelectSizes[&I];
  876. if (!Size) {
  877. // This is a new PHI/Select, check for an unsafe use of it.
  878. if (Instruction *UnsafeI = hasUnsafePHIOrSelectUse(&I, Size))
  879. return PI.setAborted(UnsafeI);
  880. }
  881. // For PHI and select operands outside the alloca, we can't nuke the entire
  882. // phi or select -- the other side might still be relevant, so we special
  883. // case them here and use a separate structure to track the operands
  884. // themselves which should be replaced with undef.
  885. // FIXME: This should instead be escaped in the event we're instrumenting
  886. // for address sanitization.
  887. if (Offset.uge(AllocSize)) {
  888. AS.DeadOperands.push_back(U);
  889. return;
  890. }
  891. insertUse(I, Offset, Size);
  892. }
  893. void visitPHINode(PHINode &PN) { visitPHINodeOrSelectInst(PN); }
  894. void visitSelectInst(SelectInst &SI) { visitPHINodeOrSelectInst(SI); }
  895. /// \brief Disable SROA entirely if there are unhandled users of the alloca.
  896. void visitInstruction(Instruction &I) { PI.setAborted(&I); }
  897. };
  898. AllocaSlices::AllocaSlices(
  899. const DataLayout &DL, AllocaInst &AI,
  900. const bool SkipHLSLMat) // HLSL Change - not sroa matrix type.
  901. :
  902. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  903. AI(AI),
  904. #endif
  905. PointerEscapingInstr(nullptr) {
  906. SliceBuilder PB(DL, AI, *this, SkipHLSLMat);
  907. SliceBuilder::PtrInfo PtrI = PB.visitPtr(AI);
  908. if (PtrI.isEscaped() || PtrI.isAborted()) {
  909. // FIXME: We should sink the escape vs. abort info into the caller nicely,
  910. // possibly by just storing the PtrInfo in the AllocaSlices.
  911. PointerEscapingInstr = PtrI.getEscapingInst() ? PtrI.getEscapingInst()
  912. : PtrI.getAbortingInst();
  913. assert(PointerEscapingInstr && "Did not track a bad instruction");
  914. return;
  915. }
  916. Slices.erase(std::remove_if(Slices.begin(), Slices.end(),
  917. [](const Slice &S) {
  918. return S.isDead();
  919. }),
  920. Slices.end());
  921. #if 0 // HLSL Change Starts - option pending
  922. #if __cplusplus >= 201103L && !defined(NDEBUG)
  923. if (SROARandomShuffleSlices) {
  924. std::mt19937 MT(static_cast<unsigned>(sys::TimeValue::now().msec()));
  925. std::shuffle(Slices.begin(), Slices.end(), MT);
  926. }
  927. #endif
  928. #endif // HLSL Change Ends - option pending
  929. // Sort the uses. This arranges for the offsets to be in ascending order,
  930. // and the sizes to be in descending order.
  931. std::sort(Slices.begin(), Slices.end());
  932. }
  933. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  934. void AllocaSlices::print(raw_ostream &OS, const_iterator I,
  935. StringRef Indent) const {
  936. printSlice(OS, I, Indent);
  937. OS << "\n";
  938. printUse(OS, I, Indent);
  939. }
  940. void AllocaSlices::printSlice(raw_ostream &OS, const_iterator I,
  941. StringRef Indent) const {
  942. OS << Indent << "[" << I->beginOffset() << "," << I->endOffset() << ")"
  943. << " slice #" << (I - begin())
  944. << (I->isSplittable() ? " (splittable)" : "");
  945. }
  946. void AllocaSlices::printUse(raw_ostream &OS, const_iterator I,
  947. StringRef Indent) const {
  948. OS << Indent << " used by: " << *I->getUse()->getUser() << "\n";
  949. }
  950. void AllocaSlices::print(raw_ostream &OS) const {
  951. if (PointerEscapingInstr) {
  952. OS << "Can't analyze slices for alloca: " << AI << "\n"
  953. << " A pointer to this alloca escaped by:\n"
  954. << " " << *PointerEscapingInstr << "\n";
  955. return;
  956. }
  957. OS << "Slices of alloca: " << AI << "\n";
  958. for (const_iterator I = begin(), E = end(); I != E; ++I)
  959. print(OS, I);
  960. }
  961. LLVM_DUMP_METHOD void AllocaSlices::dump(const_iterator I) const {
  962. print(dbgs(), I);
  963. }
  964. LLVM_DUMP_METHOD void AllocaSlices::dump() const { print(dbgs()); }
  965. #endif // !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  966. namespace {
  967. /// \brief Implementation of LoadAndStorePromoter for promoting allocas.
  968. ///
  969. /// This subclass of LoadAndStorePromoter adds overrides to handle promoting
  970. /// the loads and stores of an alloca instruction, as well as updating its
  971. /// debug information. This is used when a domtree is unavailable and thus
  972. /// mem2reg in its full form can't be used to handle promotion of allocas to
  973. /// scalar values.
  974. class AllocaPromoter : public LoadAndStorePromoter {
  975. AllocaInst &AI;
  976. DIBuilder &DIB;
  977. SmallVector<DbgDeclareInst *, 4> DDIs;
  978. SmallVector<DbgValueInst *, 4> DVIs;
  979. public:
  980. AllocaPromoter(ArrayRef<const Instruction *> Insts,
  981. SSAUpdater &S,
  982. AllocaInst &AI, DIBuilder &DIB)
  983. : LoadAndStorePromoter(Insts, S), AI(AI), DIB(DIB) {}
  984. void run(const SmallVectorImpl<Instruction *> &Insts) {
  985. // Retain the debug information attached to the alloca for use when
  986. // rewriting loads and stores.
  987. if (auto *L = LocalAsMetadata::getIfExists(&AI)) {
  988. if (auto *DINode = MetadataAsValue::getIfExists(AI.getContext(), L)) {
  989. for (User *U : DINode->users())
  990. if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
  991. DDIs.push_back(DDI);
  992. else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
  993. DVIs.push_back(DVI);
  994. }
  995. }
  996. LoadAndStorePromoter::run(Insts);
  997. // While we have the debug information, clear it off of the alloca. The
  998. // caller takes care of deleting the alloca.
  999. while (!DDIs.empty())
  1000. DDIs.pop_back_val()->eraseFromParent();
  1001. while (!DVIs.empty())
  1002. DVIs.pop_back_val()->eraseFromParent();
  1003. }
  1004. bool
  1005. isInstInList(Instruction *I,
  1006. const SmallVectorImpl<Instruction *> &Insts) const override {
  1007. Value *Ptr;
  1008. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  1009. Ptr = LI->getOperand(0);
  1010. else
  1011. Ptr = cast<StoreInst>(I)->getPointerOperand();
  1012. // Only used to detect cycles, which will be rare and quickly found as
  1013. // we're walking up a chain of defs rather than down through uses.
  1014. SmallPtrSet<Value *, 4> Visited;
  1015. do {
  1016. if (Ptr == &AI)
  1017. return true;
  1018. if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr))
  1019. Ptr = BCI->getOperand(0);
  1020. else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
  1021. Ptr = GEPI->getPointerOperand();
  1022. else
  1023. return false;
  1024. } while (Visited.insert(Ptr).second);
  1025. return false;
  1026. }
  1027. void updateDebugInfo(Instruction *Inst) const override {
  1028. for (DbgDeclareInst *DDI : DDIs)
  1029. if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
  1030. ConvertDebugDeclareToDebugValue(DDI, SI, DIB);
  1031. else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
  1032. ConvertDebugDeclareToDebugValue(DDI, LI, DIB);
  1033. for (DbgValueInst *DVI : DVIs) {
  1034. Value *Arg = nullptr;
  1035. if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
  1036. // If an argument is zero extended then use argument directly. The ZExt
  1037. // may be zapped by an optimization pass in future.
  1038. if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
  1039. Arg = dyn_cast<Argument>(ZExt->getOperand(0));
  1040. else if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
  1041. Arg = dyn_cast<Argument>(SExt->getOperand(0));
  1042. if (!Arg)
  1043. Arg = SI->getValueOperand();
  1044. } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
  1045. Arg = LI->getPointerOperand();
  1046. } else {
  1047. continue;
  1048. }
  1049. DIB.insertDbgValueIntrinsic(Arg, 0, DVI->getVariable(),
  1050. DVI->getExpression(), DVI->getDebugLoc(),
  1051. Inst);
  1052. }
  1053. }
  1054. };
  1055. } // end anon namespace
  1056. namespace {
  1057. /// \brief An optimization pass providing Scalar Replacement of Aggregates.
  1058. ///
  1059. /// This pass takes allocations which can be completely analyzed (that is, they
  1060. /// don't escape) and tries to turn them into scalar SSA values. There are
  1061. /// a few steps to this process.
  1062. ///
  1063. /// 1) It takes allocations of aggregates and analyzes the ways in which they
  1064. /// are used to try to split them into smaller allocations, ideally of
  1065. /// a single scalar data type. It will split up memcpy and memset accesses
  1066. /// as necessary and try to isolate individual scalar accesses.
  1067. /// 2) It will transform accesses into forms which are suitable for SSA value
  1068. /// promotion. This can be replacing a memset with a scalar store of an
  1069. /// integer value, or it can involve speculating operations on a PHI or
  1070. /// select to be a PHI or select of the results.
  1071. /// 3) Finally, this will try to detect a pattern of accesses which map cleanly
  1072. /// onto insert and extract operations on a vector value, and convert them to
  1073. /// this form. By doing so, it will enable promotion of vector aggregates to
  1074. /// SSA vector values.
  1075. class SROA : public FunctionPass {
  1076. const bool RequiresDomTree;
  1077. const bool SkipHLSLMat; // HLSL Change - not sroa matrix type.
  1078. LLVMContext *C;
  1079. DominatorTree *DT;
  1080. AssumptionCache *AC;
  1081. /// \brief Worklist of alloca instructions to simplify.
  1082. ///
  1083. /// Each alloca in the function is added to this. Each new alloca formed gets
  1084. /// added to it as well to recursively simplify unless that alloca can be
  1085. /// directly promoted. Finally, each time we rewrite a use of an alloca other
  1086. /// the one being actively rewritten, we add it back onto the list if not
  1087. /// already present to ensure it is re-visited.
  1088. SetVector<AllocaInst *, SmallVector<AllocaInst *, 16>> Worklist;
  1089. /// \brief A collection of instructions to delete.
  1090. /// We try to batch deletions to simplify code and make things a bit more
  1091. /// efficient.
  1092. SetVector<Instruction *, SmallVector<Instruction *, 8>> DeadInsts;
  1093. /// \brief Post-promotion worklist.
  1094. ///
  1095. /// Sometimes we discover an alloca which has a high probability of becoming
  1096. /// viable for SROA after a round of promotion takes place. In those cases,
  1097. /// the alloca is enqueued here for re-processing.
  1098. ///
  1099. /// Note that we have to be very careful to clear allocas out of this list in
  1100. /// the event they are deleted.
  1101. SetVector<AllocaInst *, SmallVector<AllocaInst *, 16>> PostPromotionWorklist;
  1102. /// \brief A collection of alloca instructions we can directly promote.
  1103. std::vector<AllocaInst *> PromotableAllocas;
  1104. /// \brief A worklist of PHIs to speculate prior to promoting allocas.
  1105. ///
  1106. /// All of these PHIs have been checked for the safety of speculation and by
  1107. /// being speculated will allow promoting allocas currently in the promotable
  1108. /// queue.
  1109. SetVector<PHINode *, SmallVector<PHINode *, 2>> SpeculatablePHIs;
  1110. /// \brief A worklist of select instructions to speculate prior to promoting
  1111. /// allocas.
  1112. ///
  1113. /// All of these select instructions have been checked for the safety of
  1114. /// speculation and by being speculated will allow promoting allocas
  1115. /// currently in the promotable queue.
  1116. SetVector<SelectInst *, SmallVector<SelectInst *, 2>> SpeculatableSelects;
  1117. public:
  1118. SROA(bool RequiresDomTree = true, bool SkipHLSLMat = true)
  1119. : FunctionPass(ID), RequiresDomTree(RequiresDomTree),
  1120. SkipHLSLMat(SkipHLSLMat), // HLSL Change - not sroa matrix type.
  1121. C(nullptr), DT(nullptr) {
  1122. initializeSROAPass(*PassRegistry::getPassRegistry());
  1123. }
  1124. bool runOnFunction(Function &F) override;
  1125. void getAnalysisUsage(AnalysisUsage &AU) const override;
  1126. const char *getPassName() const override { return "SROA"; }
  1127. static char ID;
  1128. private:
  1129. friend class PHIOrSelectSpeculator;
  1130. friend class AllocaSliceRewriter;
  1131. bool presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS);
  1132. AllocaInst *rewritePartition(AllocaInst &AI, AllocaSlices &AS,
  1133. AllocaSlices::Partition &P);
  1134. bool splitAlloca(AllocaInst &AI, AllocaSlices &AS);
  1135. bool runOnAlloca(AllocaInst &AI);
  1136. void clobberUse(Use &U);
  1137. void deleteDeadInstructions(SmallPtrSetImpl<AllocaInst *> &DeletedAllocas);
  1138. bool promoteAllocas(Function &F);
  1139. };
  1140. }
  1141. char SROA::ID = 0;
  1142. FunctionPass *llvm::createSROAPass(bool RequiresDomTree, bool SkipHLSLMat) {
  1143. return new SROA(RequiresDomTree, SkipHLSLMat);
  1144. }
  1145. INITIALIZE_PASS_BEGIN(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
  1146. false)
  1147. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  1148. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  1149. INITIALIZE_PASS_END(SROA, "sroa", "Scalar Replacement Of Aggregates", false,
  1150. false)
  1151. /// Walk the range of a partitioning looking for a common type to cover this
  1152. /// sequence of slices.
  1153. static Type *findCommonType(AllocaSlices::const_iterator B,
  1154. AllocaSlices::const_iterator E,
  1155. uint64_t EndOffset) {
  1156. Type *Ty = nullptr;
  1157. bool TyIsCommon = true;
  1158. IntegerType *ITy = nullptr;
  1159. // Note that we need to look at *every* alloca slice's Use to ensure we
  1160. // always get consistent results regardless of the order of slices.
  1161. for (AllocaSlices::const_iterator I = B; I != E; ++I) {
  1162. Use *U = I->getUse();
  1163. if (isa<IntrinsicInst>(*U->getUser()))
  1164. continue;
  1165. if (I->beginOffset() != B->beginOffset() || I->endOffset() != EndOffset)
  1166. continue;
  1167. Type *UserTy = nullptr;
  1168. if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
  1169. UserTy = LI->getType();
  1170. } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
  1171. UserTy = SI->getValueOperand()->getType();
  1172. }
  1173. if (IntegerType *UserITy = dyn_cast_or_null<IntegerType>(UserTy)) {
  1174. // If the type is larger than the partition, skip it. We only encounter
  1175. // this for split integer operations where we want to use the type of the
  1176. // entity causing the split. Also skip if the type is not a byte width
  1177. // multiple.
  1178. if (UserITy->getBitWidth() % 8 != 0 ||
  1179. UserITy->getBitWidth() / 8 > (EndOffset - B->beginOffset()))
  1180. continue;
  1181. // Track the largest bitwidth integer type used in this way in case there
  1182. // is no common type.
  1183. if (!ITy || ITy->getBitWidth() < UserITy->getBitWidth())
  1184. ITy = UserITy;
  1185. }
  1186. // To avoid depending on the order of slices, Ty and TyIsCommon must not
  1187. // depend on types skipped above.
  1188. if (!UserTy || (Ty && Ty != UserTy))
  1189. TyIsCommon = false; // Give up on anything but an iN type.
  1190. else
  1191. Ty = UserTy;
  1192. }
  1193. return TyIsCommon ? Ty : ITy;
  1194. }
  1195. /// PHI instructions that use an alloca and are subsequently loaded can be
  1196. /// rewritten to load both input pointers in the pred blocks and then PHI the
  1197. /// results, allowing the load of the alloca to be promoted.
  1198. /// From this:
  1199. /// %P2 = phi [i32* %Alloca, i32* %Other]
  1200. /// %V = load i32* %P2
  1201. /// to:
  1202. /// %V1 = load i32* %Alloca -> will be mem2reg'd
  1203. /// ...
  1204. /// %V2 = load i32* %Other
  1205. /// ...
  1206. /// %V = phi [i32 %V1, i32 %V2]
  1207. ///
  1208. /// We can do this to a select if its only uses are loads and if the operands
  1209. /// to the select can be loaded unconditionally.
  1210. ///
  1211. /// FIXME: This should be hoisted into a generic utility, likely in
  1212. /// Transforms/Util/Local.h
  1213. static bool isSafePHIToSpeculate(PHINode &PN) {
  1214. // For now, we can only do this promotion if the load is in the same block
  1215. // as the PHI, and if there are no stores between the phi and load.
  1216. // TODO: Allow recursive phi users.
  1217. // TODO: Allow stores.
  1218. BasicBlock *BB = PN.getParent();
  1219. unsigned MaxAlign = 0;
  1220. bool HaveLoad = false;
  1221. for (User *U : PN.users()) {
  1222. LoadInst *LI = dyn_cast<LoadInst>(U);
  1223. if (!LI || !LI->isSimple())
  1224. return false;
  1225. // For now we only allow loads in the same block as the PHI. This is
  1226. // a common case that happens when instcombine merges two loads through
  1227. // a PHI.
  1228. if (LI->getParent() != BB)
  1229. return false;
  1230. // Ensure that there are no instructions between the PHI and the load that
  1231. // could store.
  1232. for (BasicBlock::iterator BBI = &PN; &*BBI != LI; ++BBI)
  1233. if (BBI->mayWriteToMemory())
  1234. return false;
  1235. MaxAlign = std::max(MaxAlign, LI->getAlignment());
  1236. HaveLoad = true;
  1237. }
  1238. if (!HaveLoad)
  1239. return false;
  1240. const DataLayout &DL = PN.getModule()->getDataLayout();
  1241. // We can only transform this if it is safe to push the loads into the
  1242. // predecessor blocks. The only thing to watch out for is that we can't put
  1243. // a possibly trapping load in the predecessor if it is a critical edge.
  1244. for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
  1245. TerminatorInst *TI = PN.getIncomingBlock(Idx)->getTerminator();
  1246. Value *InVal = PN.getIncomingValue(Idx);
  1247. // If the value is produced by the terminator of the predecessor (an
  1248. // invoke) or it has side-effects, there is no valid place to put a load
  1249. // in the predecessor.
  1250. if (TI == InVal || TI->mayHaveSideEffects())
  1251. return false;
  1252. // If the predecessor has a single successor, then the edge isn't
  1253. // critical.
  1254. if (TI->getNumSuccessors() == 1)
  1255. continue;
  1256. // If this pointer is always safe to load, or if we can prove that there
  1257. // is already a load in the block, then we can move the load to the pred
  1258. // block.
  1259. if (isDereferenceablePointer(InVal, DL) ||
  1260. isSafeToLoadUnconditionally(InVal, TI, MaxAlign))
  1261. continue;
  1262. return false;
  1263. }
  1264. return true;
  1265. }
  1266. static void speculatePHINodeLoads(PHINode &PN) {
  1267. DEBUG(dbgs() << " original: " << PN << "\n");
  1268. Type *LoadTy = cast<PointerType>(PN.getType())->getElementType();
  1269. IRBuilderTy PHIBuilder(&PN);
  1270. PHINode *NewPN = PHIBuilder.CreatePHI(LoadTy, PN.getNumIncomingValues(),
  1271. PN.getName() + ".sroa.speculated");
  1272. // Get the AA tags and alignment to use from one of the loads. It doesn't
  1273. // matter which one we get and if any differ.
  1274. LoadInst *SomeLoad = cast<LoadInst>(PN.user_back());
  1275. AAMDNodes AATags;
  1276. SomeLoad->getAAMetadata(AATags);
  1277. unsigned Align = SomeLoad->getAlignment();
  1278. // Rewrite all loads of the PN to use the new PHI.
  1279. while (!PN.use_empty()) {
  1280. LoadInst *LI = cast<LoadInst>(PN.user_back());
  1281. LI->replaceAllUsesWith(NewPN);
  1282. LI->eraseFromParent();
  1283. }
  1284. // Inject loads into all of the pred blocks.
  1285. for (unsigned Idx = 0, Num = PN.getNumIncomingValues(); Idx != Num; ++Idx) {
  1286. BasicBlock *Pred = PN.getIncomingBlock(Idx);
  1287. TerminatorInst *TI = Pred->getTerminator();
  1288. Value *InVal = PN.getIncomingValue(Idx);
  1289. IRBuilderTy PredBuilder(TI);
  1290. LoadInst *Load = PredBuilder.CreateLoad(
  1291. InVal, (PN.getName() + ".sroa.speculate.load." + Pred->getName()));
  1292. ++NumLoadsSpeculated;
  1293. Load->setAlignment(Align);
  1294. if (AATags)
  1295. Load->setAAMetadata(AATags);
  1296. NewPN->addIncoming(Load, Pred);
  1297. }
  1298. DEBUG(dbgs() << " speculated to: " << *NewPN << "\n");
  1299. PN.eraseFromParent();
  1300. }
  1301. /// Select instructions that use an alloca and are subsequently loaded can be
  1302. /// rewritten to load both input pointers and then select between the result,
  1303. /// allowing the load of the alloca to be promoted.
  1304. /// From this:
  1305. /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
  1306. /// %V = load i32* %P2
  1307. /// to:
  1308. /// %V1 = load i32* %Alloca -> will be mem2reg'd
  1309. /// %V2 = load i32* %Other
  1310. /// %V = select i1 %cond, i32 %V1, i32 %V2
  1311. ///
  1312. /// We can do this to a select if its only uses are loads and if the operand
  1313. /// to the select can be loaded unconditionally.
  1314. static bool isSafeSelectToSpeculate(SelectInst &SI) {
  1315. Value *TValue = SI.getTrueValue();
  1316. Value *FValue = SI.getFalseValue();
  1317. const DataLayout &DL = SI.getModule()->getDataLayout();
  1318. bool TDerefable = isDereferenceablePointer(TValue, DL);
  1319. bool FDerefable = isDereferenceablePointer(FValue, DL);
  1320. for (User *U : SI.users()) {
  1321. LoadInst *LI = dyn_cast<LoadInst>(U);
  1322. if (!LI || !LI->isSimple())
  1323. return false;
  1324. // Both operands to the select need to be dereferencable, either
  1325. // absolutely (e.g. allocas) or at this point because we can see other
  1326. // accesses to it.
  1327. if (!TDerefable &&
  1328. !isSafeToLoadUnconditionally(TValue, LI, LI->getAlignment()))
  1329. return false;
  1330. if (!FDerefable &&
  1331. !isSafeToLoadUnconditionally(FValue, LI, LI->getAlignment()))
  1332. return false;
  1333. }
  1334. return true;
  1335. }
  1336. static void speculateSelectInstLoads(SelectInst &SI) {
  1337. DEBUG(dbgs() << " original: " << SI << "\n");
  1338. IRBuilderTy IRB(&SI);
  1339. Value *TV = SI.getTrueValue();
  1340. Value *FV = SI.getFalseValue();
  1341. // Replace the loads of the select with a select of two loads.
  1342. while (!SI.use_empty()) {
  1343. LoadInst *LI = cast<LoadInst>(SI.user_back());
  1344. assert(LI->isSimple() && "We only speculate simple loads");
  1345. IRB.SetInsertPoint(LI);
  1346. LoadInst *TL =
  1347. IRB.CreateLoad(TV, LI->getName() + ".sroa.speculate.load.true");
  1348. LoadInst *FL =
  1349. IRB.CreateLoad(FV, LI->getName() + ".sroa.speculate.load.false");
  1350. NumLoadsSpeculated += 2;
  1351. // Transfer alignment and AA info if present.
  1352. TL->setAlignment(LI->getAlignment());
  1353. FL->setAlignment(LI->getAlignment());
  1354. AAMDNodes Tags;
  1355. LI->getAAMetadata(Tags);
  1356. if (Tags) {
  1357. TL->setAAMetadata(Tags);
  1358. FL->setAAMetadata(Tags);
  1359. }
  1360. Value *V = IRB.CreateSelect(SI.getCondition(), TL, FL,
  1361. LI->getName() + ".sroa.speculated");
  1362. DEBUG(dbgs() << " speculated to: " << *V << "\n");
  1363. LI->replaceAllUsesWith(V);
  1364. LI->eraseFromParent();
  1365. }
  1366. SI.eraseFromParent();
  1367. }
  1368. /// \brief Build a GEP out of a base pointer and indices.
  1369. ///
  1370. /// This will return the BasePtr if that is valid, or build a new GEP
  1371. /// instruction using the IRBuilder if GEP-ing is needed.
  1372. static Value *buildGEP(IRBuilderTy &IRB, Value *BasePtr,
  1373. SmallVectorImpl<Value *> &Indices, Twine NamePrefix) {
  1374. if (Indices.empty())
  1375. return BasePtr;
  1376. // A single zero index is a no-op, so check for this and avoid building a GEP
  1377. // in that case.
  1378. if (Indices.size() == 1 && cast<ConstantInt>(Indices.back())->isZero())
  1379. return BasePtr;
  1380. return IRB.CreateInBoundsGEP(nullptr, BasePtr, Indices,
  1381. NamePrefix + "sroa_idx");
  1382. }
  1383. /// \brief Get a natural GEP off of the BasePtr walking through Ty toward
  1384. /// TargetTy without changing the offset of the pointer.
  1385. ///
  1386. /// This routine assumes we've already established a properly offset GEP with
  1387. /// Indices, and arrived at the Ty type. The goal is to continue to GEP with
  1388. /// zero-indices down through type layers until we find one the same as
  1389. /// TargetTy. If we can't find one with the same type, we at least try to use
  1390. /// one with the same size. If none of that works, we just produce the GEP as
  1391. /// indicated by Indices to have the correct offset.
  1392. static Value *getNaturalGEPWithType(IRBuilderTy &IRB, const DataLayout &DL,
  1393. Value *BasePtr, Type *Ty, Type *TargetTy,
  1394. SmallVectorImpl<Value *> &Indices,
  1395. Twine NamePrefix) {
  1396. if (Ty == TargetTy)
  1397. return buildGEP(IRB, BasePtr, Indices, NamePrefix);
  1398. // Pointer size to use for the indices.
  1399. unsigned PtrSize = DL.getPointerTypeSizeInBits(BasePtr->getType());
  1400. // See if we can descend into a struct and locate a field with the correct
  1401. // type.
  1402. unsigned NumLayers = 0;
  1403. Type *ElementTy = Ty;
  1404. do {
  1405. if (ElementTy->isPointerTy())
  1406. break;
  1407. if (ArrayType *ArrayTy = dyn_cast<ArrayType>(ElementTy)) {
  1408. ElementTy = ArrayTy->getElementType();
  1409. Indices.push_back(IRB.getIntN(PtrSize, 0));
  1410. } else if (VectorType *VectorTy = dyn_cast<VectorType>(ElementTy)) {
  1411. ElementTy = VectorTy->getElementType();
  1412. Indices.push_back(IRB.getInt32(0));
  1413. } else if (StructType *STy = dyn_cast<StructType>(ElementTy)) {
  1414. if (STy->element_begin() == STy->element_end())
  1415. break; // Nothing left to descend into.
  1416. ElementTy = *STy->element_begin();
  1417. Indices.push_back(IRB.getInt32(0));
  1418. } else {
  1419. break;
  1420. }
  1421. ++NumLayers;
  1422. } while (ElementTy != TargetTy);
  1423. if (ElementTy != TargetTy)
  1424. Indices.erase(Indices.end() - NumLayers, Indices.end());
  1425. return buildGEP(IRB, BasePtr, Indices, NamePrefix);
  1426. }
  1427. /// \brief Recursively compute indices for a natural GEP.
  1428. ///
  1429. /// This is the recursive step for getNaturalGEPWithOffset that walks down the
  1430. /// element types adding appropriate indices for the GEP.
  1431. static Value *getNaturalGEPRecursively(IRBuilderTy &IRB, const DataLayout &DL,
  1432. Value *Ptr, Type *Ty, APInt &Offset,
  1433. Type *TargetTy,
  1434. SmallVectorImpl<Value *> &Indices,
  1435. Twine NamePrefix) {
  1436. if (Offset == 0)
  1437. return getNaturalGEPWithType(IRB, DL, Ptr, Ty, TargetTy, Indices,
  1438. NamePrefix);
  1439. // We can't recurse through pointer types.
  1440. if (Ty->isPointerTy())
  1441. return nullptr;
  1442. // We try to analyze GEPs over vectors here, but note that these GEPs are
  1443. // extremely poorly defined currently. The long-term goal is to remove GEPing
  1444. // over a vector from the IR completely.
  1445. if (VectorType *VecTy = dyn_cast<VectorType>(Ty)) {
  1446. unsigned ElementSizeInBits = DL.getTypeSizeInBits(VecTy->getScalarType());
  1447. if (ElementSizeInBits % 8 != 0) {
  1448. // GEPs over non-multiple of 8 size vector elements are invalid.
  1449. return nullptr;
  1450. }
  1451. APInt ElementSize(Offset.getBitWidth(), ElementSizeInBits / 8);
  1452. APInt NumSkippedElements = Offset.sdiv(ElementSize);
  1453. if (NumSkippedElements.ugt(VecTy->getNumElements()))
  1454. return nullptr;
  1455. Offset -= NumSkippedElements * ElementSize;
  1456. Indices.push_back(IRB.getInt(NumSkippedElements));
  1457. return getNaturalGEPRecursively(IRB, DL, Ptr, VecTy->getElementType(),
  1458. Offset, TargetTy, Indices, NamePrefix);
  1459. }
  1460. if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
  1461. Type *ElementTy = ArrTy->getElementType();
  1462. APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
  1463. APInt NumSkippedElements = Offset.sdiv(ElementSize);
  1464. if (NumSkippedElements.ugt(ArrTy->getNumElements()))
  1465. return nullptr;
  1466. Offset -= NumSkippedElements * ElementSize;
  1467. Indices.push_back(IRB.getInt(NumSkippedElements));
  1468. return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
  1469. Indices, NamePrefix);
  1470. }
  1471. StructType *STy = dyn_cast<StructType>(Ty);
  1472. if (!STy)
  1473. return nullptr;
  1474. const StructLayout *SL = DL.getStructLayout(STy);
  1475. uint64_t StructOffset = Offset.getZExtValue();
  1476. if (StructOffset >= SL->getSizeInBytes())
  1477. return nullptr;
  1478. unsigned Index = SL->getElementContainingOffset(StructOffset);
  1479. Offset -= APInt(Offset.getBitWidth(), SL->getElementOffset(Index));
  1480. Type *ElementTy = STy->getElementType(Index);
  1481. if (Offset.uge(DL.getTypeAllocSize(ElementTy)))
  1482. return nullptr; // The offset points into alignment padding.
  1483. Indices.push_back(IRB.getInt32(Index));
  1484. return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
  1485. Indices, NamePrefix);
  1486. }
  1487. /// \brief Get a natural GEP from a base pointer to a particular offset and
  1488. /// resulting in a particular type.
  1489. ///
  1490. /// The goal is to produce a "natural" looking GEP that works with the existing
  1491. /// composite types to arrive at the appropriate offset and element type for
  1492. /// a pointer. TargetTy is the element type the returned GEP should point-to if
  1493. /// possible. We recurse by decreasing Offset, adding the appropriate index to
  1494. /// Indices, and setting Ty to the result subtype.
  1495. ///
  1496. /// If no natural GEP can be constructed, this function returns null.
  1497. static Value *getNaturalGEPWithOffset(IRBuilderTy &IRB, const DataLayout &DL,
  1498. Value *Ptr, APInt Offset, Type *TargetTy,
  1499. SmallVectorImpl<Value *> &Indices,
  1500. Twine NamePrefix) {
  1501. PointerType *Ty = cast<PointerType>(Ptr->getType());
  1502. // Don't consider any GEPs through an i8* as natural unless the TargetTy is
  1503. // an i8.
  1504. if (Ty == IRB.getInt8PtrTy(Ty->getAddressSpace()) && TargetTy->isIntegerTy(8))
  1505. return nullptr;
  1506. Type *ElementTy = Ty->getElementType();
  1507. if (!ElementTy->isSized())
  1508. return nullptr; // We can't GEP through an unsized element.
  1509. APInt ElementSize(Offset.getBitWidth(), DL.getTypeAllocSize(ElementTy));
  1510. if (ElementSize == 0)
  1511. return nullptr; // Zero-length arrays can't help us build a natural GEP.
  1512. APInt NumSkippedElements = Offset.sdiv(ElementSize);
  1513. Offset -= NumSkippedElements * ElementSize;
  1514. Indices.push_back(IRB.getInt(NumSkippedElements));
  1515. return getNaturalGEPRecursively(IRB, DL, Ptr, ElementTy, Offset, TargetTy,
  1516. Indices, NamePrefix);
  1517. }
  1518. /// \brief Compute an adjusted pointer from Ptr by Offset bytes where the
  1519. /// resulting pointer has PointerTy.
  1520. ///
  1521. /// This tries very hard to compute a "natural" GEP which arrives at the offset
  1522. /// and produces the pointer type desired. Where it cannot, it will try to use
  1523. /// the natural GEP to arrive at the offset and bitcast to the type. Where that
  1524. /// fails, it will try to use an existing i8* and GEP to the byte offset and
  1525. /// bitcast to the type.
  1526. ///
  1527. /// The strategy for finding the more natural GEPs is to peel off layers of the
  1528. /// pointer, walking back through bit casts and GEPs, searching for a base
  1529. /// pointer from which we can compute a natural GEP with the desired
  1530. /// properties. The algorithm tries to fold as many constant indices into
  1531. /// a single GEP as possible, thus making each GEP more independent of the
  1532. /// surrounding code.
  1533. static Value *getAdjustedPtr(IRBuilderTy &IRB, const DataLayout &DL, Value *Ptr,
  1534. APInt Offset, Type *PointerTy, Twine NamePrefix) {
  1535. // Even though we don't look through PHI nodes, we could be called on an
  1536. // instruction in an unreachable block, which may be on a cycle.
  1537. SmallPtrSet<Value *, 4> Visited;
  1538. Visited.insert(Ptr);
  1539. SmallVector<Value *, 4> Indices;
  1540. // We may end up computing an offset pointer that has the wrong type. If we
  1541. // never are able to compute one directly that has the correct type, we'll
  1542. // fall back to it, so keep it and the base it was computed from around here.
  1543. Value *OffsetPtr = nullptr;
  1544. Value *OffsetBasePtr;
  1545. // Remember any i8 pointer we come across to re-use if we need to do a raw
  1546. // byte offset.
  1547. Value *Int8Ptr = nullptr;
  1548. APInt Int8PtrOffset(Offset.getBitWidth(), 0);
  1549. Type *TargetTy = PointerTy->getPointerElementType();
  1550. do {
  1551. // First fold any existing GEPs into the offset.
  1552. while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
  1553. APInt GEPOffset(Offset.getBitWidth(), 0);
  1554. if (!GEP->accumulateConstantOffset(DL, GEPOffset))
  1555. break;
  1556. Offset += GEPOffset;
  1557. Ptr = GEP->getPointerOperand();
  1558. if (!Visited.insert(Ptr).second)
  1559. break;
  1560. }
  1561. // See if we can perform a natural GEP here.
  1562. Indices.clear();
  1563. if (Value *P = getNaturalGEPWithOffset(IRB, DL, Ptr, Offset, TargetTy,
  1564. Indices, NamePrefix)) {
  1565. // If we have a new natural pointer at the offset, clear out any old
  1566. // offset pointer we computed. Unless it is the base pointer or
  1567. // a non-instruction, we built a GEP we don't need. Zap it.
  1568. if (OffsetPtr && OffsetPtr != OffsetBasePtr)
  1569. if (Instruction *I = dyn_cast<Instruction>(OffsetPtr)) {
  1570. assert(I->use_empty() && "Built a GEP with uses some how!");
  1571. I->eraseFromParent();
  1572. }
  1573. OffsetPtr = P;
  1574. OffsetBasePtr = Ptr;
  1575. // If we also found a pointer of the right type, we're done.
  1576. if (P->getType() == PointerTy)
  1577. return P;
  1578. }
  1579. // Stash this pointer if we've found an i8*.
  1580. if (Ptr->getType()->isIntegerTy(8)) {
  1581. Int8Ptr = Ptr;
  1582. Int8PtrOffset = Offset;
  1583. }
  1584. // Peel off a layer of the pointer and update the offset appropriately.
  1585. if (Operator::getOpcode(Ptr) == Instruction::BitCast) {
  1586. Ptr = cast<Operator>(Ptr)->getOperand(0);
  1587. } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Ptr)) {
  1588. if (GA->mayBeOverridden())
  1589. break;
  1590. Ptr = GA->getAliasee();
  1591. } else {
  1592. break;
  1593. }
  1594. assert(Ptr->getType()->isPointerTy() && "Unexpected operand type!");
  1595. } while (Visited.insert(Ptr).second);
  1596. if (!OffsetPtr) {
  1597. if (!Int8Ptr) {
  1598. Int8Ptr = IRB.CreateBitCast(
  1599. Ptr, IRB.getInt8PtrTy(PointerTy->getPointerAddressSpace()),
  1600. NamePrefix + "sroa_raw_cast");
  1601. Int8PtrOffset = Offset;
  1602. }
  1603. OffsetPtr = Int8PtrOffset == 0
  1604. ? Int8Ptr
  1605. : IRB.CreateInBoundsGEP(IRB.getInt8Ty(), Int8Ptr,
  1606. IRB.getInt(Int8PtrOffset),
  1607. NamePrefix + "sroa_raw_idx");
  1608. }
  1609. Ptr = OffsetPtr;
  1610. // On the off chance we were targeting i8*, guard the bitcast here.
  1611. if (Ptr->getType() != PointerTy)
  1612. Ptr = IRB.CreateBitCast(Ptr, PointerTy, NamePrefix + "sroa_cast");
  1613. return Ptr;
  1614. }
  1615. /// \brief Compute the adjusted alignment for a load or store from an offset.
  1616. static unsigned getAdjustedAlignment(Instruction *I, uint64_t Offset,
  1617. const DataLayout &DL) {
  1618. unsigned Alignment;
  1619. Type *Ty;
  1620. if (auto *LI = dyn_cast<LoadInst>(I)) {
  1621. Alignment = LI->getAlignment();
  1622. Ty = LI->getType();
  1623. } else if (auto *SI = dyn_cast<StoreInst>(I)) {
  1624. Alignment = SI->getAlignment();
  1625. Ty = SI->getValueOperand()->getType();
  1626. } else {
  1627. llvm_unreachable("Only loads and stores are allowed!");
  1628. }
  1629. if (!Alignment)
  1630. Alignment = DL.getABITypeAlignment(Ty);
  1631. return MinAlign(Alignment, Offset);
  1632. }
  1633. /// \brief Test whether we can convert a value from the old to the new type.
  1634. ///
  1635. /// This predicate should be used to guard calls to convertValue in order to
  1636. /// ensure that we only try to convert viable values. The strategy is that we
  1637. /// will peel off single element struct and array wrappings to get to an
  1638. /// underlying value, and convert that value.
  1639. static bool canConvertValue(const DataLayout &DL, Type *OldTy, Type *NewTy) {
  1640. if (OldTy == NewTy)
  1641. return true;
  1642. // For integer types, we can't handle any bit-width differences. This would
  1643. // break both vector conversions with extension and introduce endianness
  1644. // issues when in conjunction with loads and stores.
  1645. if (isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) {
  1646. assert(cast<IntegerType>(OldTy)->getBitWidth() !=
  1647. cast<IntegerType>(NewTy)->getBitWidth() &&
  1648. "We can't have the same bitwidth for different int types");
  1649. return false;
  1650. }
  1651. if (DL.getTypeSizeInBits(NewTy) != DL.getTypeSizeInBits(OldTy))
  1652. return false;
  1653. if (!NewTy->isSingleValueType() || !OldTy->isSingleValueType())
  1654. return false;
  1655. // We can convert pointers to integers and vice-versa. Same for vectors
  1656. // of pointers and integers.
  1657. OldTy = OldTy->getScalarType();
  1658. NewTy = NewTy->getScalarType();
  1659. if (NewTy->isPointerTy() || OldTy->isPointerTy()) {
  1660. if (NewTy->isPointerTy() && OldTy->isPointerTy())
  1661. return true;
  1662. if (NewTy->isIntegerTy() || OldTy->isIntegerTy())
  1663. return true;
  1664. return false;
  1665. }
  1666. return true;
  1667. }
  1668. /// \brief Generic routine to convert an SSA value to a value of a different
  1669. /// type.
  1670. ///
  1671. /// This will try various different casting techniques, such as bitcasts,
  1672. /// inttoptr, and ptrtoint casts. Use the \c canConvertValue predicate to test
  1673. /// two types for viability with this routine.
  1674. static Value *convertValue(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
  1675. Type *NewTy) {
  1676. Type *OldTy = V->getType();
  1677. assert(canConvertValue(DL, OldTy, NewTy) && "Value not convertable to type");
  1678. if (OldTy == NewTy)
  1679. return V;
  1680. assert(!(isa<IntegerType>(OldTy) && isa<IntegerType>(NewTy)) &&
  1681. "Integer types must be the exact same to convert.");
  1682. // See if we need inttoptr for this type pair. A cast involving both scalars
  1683. // and vectors requires and additional bitcast.
  1684. if (OldTy->getScalarType()->isIntegerTy() &&
  1685. NewTy->getScalarType()->isPointerTy()) {
  1686. // Expand <2 x i32> to i8* --> <2 x i32> to i64 to i8*
  1687. if (OldTy->isVectorTy() && !NewTy->isVectorTy())
  1688. return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
  1689. NewTy);
  1690. // Expand i128 to <2 x i8*> --> i128 to <2 x i64> to <2 x i8*>
  1691. if (!OldTy->isVectorTy() && NewTy->isVectorTy())
  1692. return IRB.CreateIntToPtr(IRB.CreateBitCast(V, DL.getIntPtrType(NewTy)),
  1693. NewTy);
  1694. return IRB.CreateIntToPtr(V, NewTy);
  1695. }
  1696. // See if we need ptrtoint for this type pair. A cast involving both scalars
  1697. // and vectors requires and additional bitcast.
  1698. if (OldTy->getScalarType()->isPointerTy() &&
  1699. NewTy->getScalarType()->isIntegerTy()) {
  1700. // Expand <2 x i8*> to i128 --> <2 x i8*> to <2 x i64> to i128
  1701. if (OldTy->isVectorTy() && !NewTy->isVectorTy())
  1702. return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
  1703. NewTy);
  1704. // Expand i8* to <2 x i32> --> i8* to i64 to <2 x i32>
  1705. if (!OldTy->isVectorTy() && NewTy->isVectorTy())
  1706. return IRB.CreateBitCast(IRB.CreatePtrToInt(V, DL.getIntPtrType(OldTy)),
  1707. NewTy);
  1708. return IRB.CreatePtrToInt(V, NewTy);
  1709. }
  1710. return IRB.CreateBitCast(V, NewTy);
  1711. }
  1712. /// \brief Test whether the given slice use can be promoted to a vector.
  1713. ///
  1714. /// This function is called to test each entry in a partioning which is slated
  1715. /// for a single slice.
  1716. static bool isVectorPromotionViableForSlice(AllocaSlices::Partition &P,
  1717. const Slice &S, VectorType *Ty,
  1718. uint64_t ElementSize,
  1719. const DataLayout &DL) {
  1720. // First validate the slice offsets.
  1721. uint64_t BeginOffset =
  1722. std::max(S.beginOffset(), P.beginOffset()) - P.beginOffset();
  1723. uint64_t BeginIndex = BeginOffset / ElementSize;
  1724. if (BeginIndex * ElementSize != BeginOffset ||
  1725. BeginIndex >= Ty->getNumElements())
  1726. return false;
  1727. uint64_t EndOffset =
  1728. std::min(S.endOffset(), P.endOffset()) - P.beginOffset();
  1729. uint64_t EndIndex = EndOffset / ElementSize;
  1730. if (EndIndex * ElementSize != EndOffset || EndIndex > Ty->getNumElements())
  1731. return false;
  1732. assert(EndIndex > BeginIndex && "Empty vector!");
  1733. uint64_t NumElements = EndIndex - BeginIndex;
  1734. Type *SliceTy = (NumElements == 1)
  1735. ? Ty->getElementType()
  1736. : VectorType::get(Ty->getElementType(), NumElements);
  1737. Type *SplitIntTy =
  1738. Type::getIntNTy(Ty->getContext(), NumElements * ElementSize * 8);
  1739. Use *U = S.getUse();
  1740. if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
  1741. if (MI->isVolatile())
  1742. return false;
  1743. if (!S.isSplittable())
  1744. return false; // Skip any unsplittable intrinsics.
  1745. } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
  1746. if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
  1747. II->getIntrinsicID() != Intrinsic::lifetime_end)
  1748. return false;
  1749. } else if (U->get()->getType()->getPointerElementType()->isStructTy()) {
  1750. // Disable vector promotion when there are loads or stores of an FCA.
  1751. return false;
  1752. } else if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
  1753. if (LI->isVolatile())
  1754. return false;
  1755. Type *LTy = LI->getType();
  1756. if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
  1757. assert(LTy->isIntegerTy());
  1758. LTy = SplitIntTy;
  1759. }
  1760. if (!canConvertValue(DL, SliceTy, LTy))
  1761. return false;
  1762. } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
  1763. if (SI->isVolatile())
  1764. return false;
  1765. Type *STy = SI->getValueOperand()->getType();
  1766. if (P.beginOffset() > S.beginOffset() || P.endOffset() < S.endOffset()) {
  1767. assert(STy->isIntegerTy());
  1768. STy = SplitIntTy;
  1769. }
  1770. if (!canConvertValue(DL, STy, SliceTy))
  1771. return false;
  1772. } else {
  1773. return false;
  1774. }
  1775. return true;
  1776. }
  1777. /// \brief Test whether the given alloca partitioning and range of slices can be
  1778. /// promoted to a vector.
  1779. ///
  1780. /// This is a quick test to check whether we can rewrite a particular alloca
  1781. /// partition (and its newly formed alloca) into a vector alloca with only
  1782. /// whole-vector loads and stores such that it could be promoted to a vector
  1783. /// SSA value. We only can ensure this for a limited set of operations, and we
  1784. /// don't want to do the rewrites unless we are confident that the result will
  1785. /// be promotable, so we have an early test here.
  1786. static VectorType *isVectorPromotionViable(AllocaSlices::Partition &P,
  1787. const DataLayout &DL) {
  1788. // Collect the candidate types for vector-based promotion. Also track whether
  1789. // we have different element types.
  1790. SmallVector<VectorType *, 4> CandidateTys;
  1791. Type *CommonEltTy = nullptr;
  1792. bool HaveCommonEltTy = true;
  1793. auto CheckCandidateType = [&](Type *Ty) {
  1794. if (auto *VTy = dyn_cast<VectorType>(Ty)) {
  1795. CandidateTys.push_back(VTy);
  1796. if (!CommonEltTy)
  1797. CommonEltTy = VTy->getElementType();
  1798. else if (CommonEltTy != VTy->getElementType())
  1799. HaveCommonEltTy = false;
  1800. }
  1801. };
  1802. // Consider any loads or stores that are the exact size of the slice.
  1803. for (const Slice &S : P)
  1804. if (S.beginOffset() == P.beginOffset() &&
  1805. S.endOffset() == P.endOffset()) {
  1806. if (auto *LI = dyn_cast<LoadInst>(S.getUse()->getUser()))
  1807. CheckCandidateType(LI->getType());
  1808. else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser()))
  1809. CheckCandidateType(SI->getValueOperand()->getType());
  1810. }
  1811. // If we didn't find a vector type, nothing to do here.
  1812. if (CandidateTys.empty())
  1813. return nullptr;
  1814. // Remove non-integer vector types if we had multiple common element types.
  1815. // FIXME: It'd be nice to replace them with integer vector types, but we can't
  1816. // do that until all the backends are known to produce good code for all
  1817. // integer vector types.
  1818. if (!HaveCommonEltTy) {
  1819. CandidateTys.erase(std::remove_if(CandidateTys.begin(), CandidateTys.end(),
  1820. [](VectorType *VTy) {
  1821. return !VTy->getElementType()->isIntegerTy();
  1822. }),
  1823. CandidateTys.end());
  1824. // If there were no integer vector types, give up.
  1825. if (CandidateTys.empty())
  1826. return nullptr;
  1827. // Rank the remaining candidate vector types. This is easy because we know
  1828. // they're all integer vectors. We sort by ascending number of elements.
  1829. auto RankVectorTypes = [&DL](VectorType *RHSTy, VectorType *LHSTy) {
  1830. assert(DL.getTypeSizeInBits(RHSTy) == DL.getTypeSizeInBits(LHSTy) &&
  1831. "Cannot have vector types of different sizes!");
  1832. assert(RHSTy->getElementType()->isIntegerTy() &&
  1833. "All non-integer types eliminated!");
  1834. assert(LHSTy->getElementType()->isIntegerTy() &&
  1835. "All non-integer types eliminated!");
  1836. (void)DL;// HLSL Change - unused var
  1837. return RHSTy->getNumElements() < LHSTy->getNumElements();
  1838. };
  1839. std::sort(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes);
  1840. CandidateTys.erase(
  1841. std::unique(CandidateTys.begin(), CandidateTys.end(), RankVectorTypes),
  1842. CandidateTys.end());
  1843. } else {
  1844. // The only way to have the same element type in every vector type is to
  1845. // have the same vector type. Check that and remove all but one.
  1846. #ifndef NDEBUG
  1847. for (VectorType *VTy : CandidateTys) {
  1848. assert(VTy->getElementType() == CommonEltTy &&
  1849. "Unaccounted for element type!");
  1850. assert(VTy == CandidateTys[0] &&
  1851. "Different vector types with the same element type!");
  1852. }
  1853. #endif
  1854. CandidateTys.resize(1);
  1855. }
  1856. // Try each vector type, and return the one which works.
  1857. auto CheckVectorTypeForPromotion = [&](VectorType *VTy) {
  1858. uint64_t ElementSize = DL.getTypeSizeInBits(VTy->getElementType());
  1859. // While the definition of LLVM vectors is bitpacked, we don't support sizes
  1860. // that aren't byte sized.
  1861. if (ElementSize % 8)
  1862. return false;
  1863. assert((DL.getTypeSizeInBits(VTy) % 8) == 0 &&
  1864. "vector size not a multiple of element size?");
  1865. ElementSize /= 8;
  1866. for (const Slice &S : P)
  1867. if (!isVectorPromotionViableForSlice(P, S, VTy, ElementSize, DL))
  1868. return false;
  1869. for (const Slice *S : P.splitSliceTails())
  1870. if (!isVectorPromotionViableForSlice(P, *S, VTy, ElementSize, DL))
  1871. return false;
  1872. return true;
  1873. };
  1874. for (VectorType *VTy : CandidateTys)
  1875. if (CheckVectorTypeForPromotion(VTy))
  1876. return VTy;
  1877. return nullptr;
  1878. }
  1879. /// \brief Test whether a slice of an alloca is valid for integer widening.
  1880. ///
  1881. /// This implements the necessary checking for the \c isIntegerWideningViable
  1882. /// test below on a single slice of the alloca.
  1883. static bool isIntegerWideningViableForSlice(const Slice &S,
  1884. uint64_t AllocBeginOffset,
  1885. Type *AllocaTy,
  1886. const DataLayout &DL,
  1887. bool &WholeAllocaOp) {
  1888. uint64_t Size = DL.getTypeStoreSize(AllocaTy);
  1889. uint64_t RelBegin = S.beginOffset() - AllocBeginOffset;
  1890. uint64_t RelEnd = S.endOffset() - AllocBeginOffset;
  1891. // We can't reasonably handle cases where the load or store extends past
  1892. // the end of the aloca's type and into its padding.
  1893. if (RelEnd > Size)
  1894. return false;
  1895. Use *U = S.getUse();
  1896. if (LoadInst *LI = dyn_cast<LoadInst>(U->getUser())) {
  1897. if (LI->isVolatile())
  1898. return false;
  1899. // We can't handle loads that extend past the allocated memory.
  1900. if (DL.getTypeStoreSize(LI->getType()) > Size)
  1901. return false;
  1902. // Note that we don't count vector loads or stores as whole-alloca
  1903. // operations which enable integer widening because we would prefer to use
  1904. // vector widening instead.
  1905. if (!isa<VectorType>(LI->getType()) && RelBegin == 0 && RelEnd == Size)
  1906. WholeAllocaOp = true;
  1907. if (IntegerType *ITy = dyn_cast<IntegerType>(LI->getType())) {
  1908. if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
  1909. return false;
  1910. } else if (RelBegin != 0 || RelEnd != Size ||
  1911. !canConvertValue(DL, AllocaTy, LI->getType())) {
  1912. // Non-integer loads need to be convertible from the alloca type so that
  1913. // they are promotable.
  1914. return false;
  1915. }
  1916. } else if (StoreInst *SI = dyn_cast<StoreInst>(U->getUser())) {
  1917. Type *ValueTy = SI->getValueOperand()->getType();
  1918. if (SI->isVolatile())
  1919. return false;
  1920. // We can't handle stores that extend past the allocated memory.
  1921. if (DL.getTypeStoreSize(ValueTy) > Size)
  1922. return false;
  1923. // Note that we don't count vector loads or stores as whole-alloca
  1924. // operations which enable integer widening because we would prefer to use
  1925. // vector widening instead.
  1926. if (!isa<VectorType>(ValueTy) && RelBegin == 0 && RelEnd == Size)
  1927. WholeAllocaOp = true;
  1928. if (IntegerType *ITy = dyn_cast<IntegerType>(ValueTy)) {
  1929. if (ITy->getBitWidth() < DL.getTypeStoreSizeInBits(ITy))
  1930. return false;
  1931. } else if (RelBegin != 0 || RelEnd != Size ||
  1932. !canConvertValue(DL, ValueTy, AllocaTy)) {
  1933. // Non-integer stores need to be convertible to the alloca type so that
  1934. // they are promotable.
  1935. return false;
  1936. }
  1937. } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U->getUser())) {
  1938. if (MI->isVolatile() || !isa<Constant>(MI->getLength()))
  1939. return false;
  1940. if (!S.isSplittable())
  1941. return false; // Skip any unsplittable intrinsics.
  1942. } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U->getUser())) {
  1943. if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
  1944. II->getIntrinsicID() != Intrinsic::lifetime_end)
  1945. return false;
  1946. } else {
  1947. return false;
  1948. }
  1949. return true;
  1950. }
  1951. /// \brief Test whether the given alloca partition's integer operations can be
  1952. /// widened to promotable ones.
  1953. ///
  1954. /// This is a quick test to check whether we can rewrite the integer loads and
  1955. /// stores to a particular alloca into wider loads and stores and be able to
  1956. /// promote the resulting alloca.
  1957. static bool isIntegerWideningViable(AllocaSlices::Partition &P, Type *AllocaTy,
  1958. const DataLayout &DL) {
  1959. uint64_t SizeInBits = DL.getTypeSizeInBits(AllocaTy);
  1960. // Don't create integer types larger than the maximum bitwidth.
  1961. if (SizeInBits > IntegerType::MAX_INT_BITS)
  1962. return false;
  1963. // Don't try to handle allocas with bit-padding.
  1964. if (SizeInBits != DL.getTypeStoreSizeInBits(AllocaTy))
  1965. return false;
  1966. // We need to ensure that an integer type with the appropriate bitwidth can
  1967. // be converted to the alloca type, whatever that is. We don't want to force
  1968. // the alloca itself to have an integer type if there is a more suitable one.
  1969. Type *IntTy = Type::getIntNTy(AllocaTy->getContext(), SizeInBits);
  1970. if (!canConvertValue(DL, AllocaTy, IntTy) ||
  1971. !canConvertValue(DL, IntTy, AllocaTy))
  1972. return false;
  1973. // While examining uses, we ensure that the alloca has a covering load or
  1974. // store. We don't want to widen the integer operations only to fail to
  1975. // promote due to some other unsplittable entry (which we may make splittable
  1976. // later). However, if there are only splittable uses, go ahead and assume
  1977. // that we cover the alloca.
  1978. // FIXME: We shouldn't consider split slices that happen to start in the
  1979. // partition here...
  1980. bool WholeAllocaOp =
  1981. P.begin() != P.end() ? false : DL.isLegalInteger(SizeInBits);
  1982. for (const Slice &S : P)
  1983. if (!isIntegerWideningViableForSlice(S, P.beginOffset(), AllocaTy, DL,
  1984. WholeAllocaOp))
  1985. return false;
  1986. for (const Slice *S : P.splitSliceTails())
  1987. if (!isIntegerWideningViableForSlice(*S, P.beginOffset(), AllocaTy, DL,
  1988. WholeAllocaOp))
  1989. return false;
  1990. return WholeAllocaOp;
  1991. }
  1992. static Value *extractInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *V,
  1993. IntegerType *Ty, uint64_t Offset,
  1994. const Twine &Name) {
  1995. DEBUG(dbgs() << " start: " << *V << "\n");
  1996. IntegerType *IntTy = cast<IntegerType>(V->getType());
  1997. assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
  1998. "Element extends past full value");
  1999. uint64_t ShAmt = 8 * Offset;
  2000. if (DL.isBigEndian())
  2001. ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
  2002. if (ShAmt) {
  2003. V = IRB.CreateLShr(V, ShAmt, Name + ".shift");
  2004. DEBUG(dbgs() << " shifted: " << *V << "\n");
  2005. }
  2006. assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
  2007. "Cannot extract to a larger integer!");
  2008. if (Ty != IntTy) {
  2009. V = IRB.CreateTrunc(V, Ty, Name + ".trunc");
  2010. DEBUG(dbgs() << " trunced: " << *V << "\n");
  2011. }
  2012. return V;
  2013. }
  2014. static Value *insertInteger(const DataLayout &DL, IRBuilderTy &IRB, Value *Old,
  2015. Value *V, uint64_t Offset, const Twine &Name) {
  2016. IntegerType *IntTy = cast<IntegerType>(Old->getType());
  2017. IntegerType *Ty = cast<IntegerType>(V->getType());
  2018. assert(Ty->getBitWidth() <= IntTy->getBitWidth() &&
  2019. "Cannot insert a larger integer!");
  2020. DEBUG(dbgs() << " start: " << *V << "\n");
  2021. if (Ty != IntTy) {
  2022. V = IRB.CreateZExt(V, IntTy, Name + ".ext");
  2023. DEBUG(dbgs() << " extended: " << *V << "\n");
  2024. }
  2025. assert(DL.getTypeStoreSize(Ty) + Offset <= DL.getTypeStoreSize(IntTy) &&
  2026. "Element store outside of alloca store");
  2027. uint64_t ShAmt = 8 * Offset;
  2028. if (DL.isBigEndian())
  2029. ShAmt = 8 * (DL.getTypeStoreSize(IntTy) - DL.getTypeStoreSize(Ty) - Offset);
  2030. if (ShAmt) {
  2031. V = IRB.CreateShl(V, ShAmt, Name + ".shift");
  2032. DEBUG(dbgs() << " shifted: " << *V << "\n");
  2033. }
  2034. if (ShAmt || Ty->getBitWidth() < IntTy->getBitWidth()) {
  2035. APInt Mask = ~Ty->getMask().zext(IntTy->getBitWidth()).shl(ShAmt);
  2036. Old = IRB.CreateAnd(Old, Mask, Name + ".mask");
  2037. DEBUG(dbgs() << " masked: " << *Old << "\n");
  2038. V = IRB.CreateOr(Old, V, Name + ".insert");
  2039. DEBUG(dbgs() << " inserted: " << *V << "\n");
  2040. }
  2041. return V;
  2042. }
  2043. static Value *extractVector(IRBuilderTy &IRB, Value *V, unsigned BeginIndex,
  2044. unsigned EndIndex, const Twine &Name) {
  2045. VectorType *VecTy = cast<VectorType>(V->getType());
  2046. unsigned NumElements = EndIndex - BeginIndex;
  2047. assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
  2048. if (NumElements == VecTy->getNumElements())
  2049. return V;
  2050. if (NumElements == 1) {
  2051. V = IRB.CreateExtractElement(V, IRB.getInt32(BeginIndex),
  2052. Name + ".extract");
  2053. DEBUG(dbgs() << " extract: " << *V << "\n");
  2054. return V;
  2055. }
  2056. SmallVector<Constant *, 8> Mask;
  2057. Mask.reserve(NumElements);
  2058. for (unsigned i = BeginIndex; i != EndIndex; ++i)
  2059. Mask.push_back(IRB.getInt32(i));
  2060. V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
  2061. ConstantVector::get(Mask), Name + ".extract");
  2062. DEBUG(dbgs() << " shuffle: " << *V << "\n");
  2063. return V;
  2064. }
  2065. static Value *insertVector(IRBuilderTy &IRB, Value *Old, Value *V,
  2066. unsigned BeginIndex, const Twine &Name) {
  2067. VectorType *VecTy = cast<VectorType>(Old->getType());
  2068. assert(VecTy && "Can only insert a vector into a vector");
  2069. VectorType *Ty = dyn_cast<VectorType>(V->getType());
  2070. if (!Ty) {
  2071. // Single element to insert.
  2072. V = IRB.CreateInsertElement(Old, V, IRB.getInt32(BeginIndex),
  2073. Name + ".insert");
  2074. DEBUG(dbgs() << " insert: " << *V << "\n");
  2075. return V;
  2076. }
  2077. assert(Ty->getNumElements() <= VecTy->getNumElements() &&
  2078. "Too many elements!");
  2079. if (Ty->getNumElements() == VecTy->getNumElements()) {
  2080. assert(V->getType() == VecTy && "Vector type mismatch");
  2081. return V;
  2082. }
  2083. unsigned EndIndex = BeginIndex + Ty->getNumElements();
  2084. // When inserting a smaller vector into the larger to store, we first
  2085. // use a shuffle vector to widen it with undef elements, and then
  2086. // a second shuffle vector to select between the loaded vector and the
  2087. // incoming vector.
  2088. SmallVector<Constant *, 8> Mask;
  2089. Mask.reserve(VecTy->getNumElements());
  2090. for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
  2091. if (i >= BeginIndex && i < EndIndex)
  2092. Mask.push_back(IRB.getInt32(i - BeginIndex));
  2093. else
  2094. Mask.push_back(UndefValue::get(IRB.getInt32Ty()));
  2095. V = IRB.CreateShuffleVector(V, UndefValue::get(V->getType()),
  2096. ConstantVector::get(Mask), Name + ".expand");
  2097. DEBUG(dbgs() << " shuffle: " << *V << "\n");
  2098. Mask.clear();
  2099. for (unsigned i = 0; i != VecTy->getNumElements(); ++i)
  2100. Mask.push_back(IRB.getInt1(i >= BeginIndex && i < EndIndex));
  2101. V = IRB.CreateSelect(ConstantVector::get(Mask), V, Old, Name + "blend");
  2102. DEBUG(dbgs() << " blend: " << *V << "\n");
  2103. return V;
  2104. }
  2105. namespace {
  2106. /// \brief Visitor to rewrite instructions using p particular slice of an alloca
  2107. /// to use a new alloca.
  2108. ///
  2109. /// Also implements the rewriting to vector-based accesses when the partition
  2110. /// passes the isVectorPromotionViable predicate. Most of the rewriting logic
  2111. /// lives here.
  2112. class AllocaSliceRewriter : public InstVisitor<AllocaSliceRewriter, bool> {
  2113. // Befriend the base class so it can delegate to private visit methods.
  2114. friend class llvm::InstVisitor<AllocaSliceRewriter, bool>;
  2115. typedef llvm::InstVisitor<AllocaSliceRewriter, bool> Base;
  2116. const DataLayout &DL;
  2117. AllocaSlices &AS;
  2118. SROA &Pass;
  2119. AllocaInst &OldAI, &NewAI;
  2120. const uint64_t NewAllocaBeginOffset, NewAllocaEndOffset;
  2121. Type *NewAllocaTy;
  2122. // This is a convenience and flag variable that will be null unless the new
  2123. // alloca's integer operations should be widened to this integer type due to
  2124. // passing isIntegerWideningViable above. If it is non-null, the desired
  2125. // integer type will be stored here for easy access during rewriting.
  2126. IntegerType *IntTy;
  2127. // If we are rewriting an alloca partition which can be written as pure
  2128. // vector operations, we stash extra information here. When VecTy is
  2129. // non-null, we have some strict guarantees about the rewritten alloca:
  2130. // - The new alloca is exactly the size of the vector type here.
  2131. // - The accesses all either map to the entire vector or to a single
  2132. // element.
  2133. // - The set of accessing instructions is only one of those handled above
  2134. // in isVectorPromotionViable. Generally these are the same access kinds
  2135. // which are promotable via mem2reg.
  2136. VectorType *VecTy;
  2137. Type *ElementTy;
  2138. uint64_t ElementSize;
  2139. // The original offset of the slice currently being rewritten relative to
  2140. // the original alloca.
  2141. uint64_t BeginOffset, EndOffset;
  2142. // The new offsets of the slice currently being rewritten relative to the
  2143. // original alloca.
  2144. uint64_t NewBeginOffset, NewEndOffset;
  2145. uint64_t SliceSize;
  2146. bool IsSplittable;
  2147. bool IsSplit;
  2148. Use *OldUse;
  2149. Instruction *OldPtr;
  2150. // Track post-rewrite users which are PHI nodes and Selects.
  2151. SmallPtrSetImpl<PHINode *> &PHIUsers;
  2152. SmallPtrSetImpl<SelectInst *> &SelectUsers;
  2153. // Utility IR builder, whose name prefix is setup for each visited use, and
  2154. // the insertion point is set to point to the user.
  2155. IRBuilderTy IRB;
  2156. public:
  2157. AllocaSliceRewriter(const DataLayout &DL, AllocaSlices &AS, SROA &Pass,
  2158. AllocaInst &OldAI, AllocaInst &NewAI,
  2159. uint64_t NewAllocaBeginOffset,
  2160. uint64_t NewAllocaEndOffset, bool IsIntegerPromotable,
  2161. VectorType *PromotableVecTy,
  2162. SmallPtrSetImpl<PHINode *> &PHIUsers,
  2163. SmallPtrSetImpl<SelectInst *> &SelectUsers)
  2164. : DL(DL), AS(AS), Pass(Pass), OldAI(OldAI), NewAI(NewAI),
  2165. NewAllocaBeginOffset(NewAllocaBeginOffset),
  2166. NewAllocaEndOffset(NewAllocaEndOffset),
  2167. NewAllocaTy(NewAI.getAllocatedType()),
  2168. IntTy(IsIntegerPromotable
  2169. ? Type::getIntNTy(
  2170. NewAI.getContext(),
  2171. DL.getTypeSizeInBits(NewAI.getAllocatedType()))
  2172. : nullptr),
  2173. VecTy(PromotableVecTy),
  2174. ElementTy(VecTy ? VecTy->getElementType() : nullptr),
  2175. ElementSize(VecTy ? DL.getTypeSizeInBits(ElementTy) / 8 : 0),
  2176. BeginOffset(), EndOffset(), IsSplittable(), IsSplit(), OldUse(),
  2177. OldPtr(), PHIUsers(PHIUsers), SelectUsers(SelectUsers),
  2178. IRB(NewAI.getContext(), ConstantFolder()) {
  2179. if (VecTy) {
  2180. assert((DL.getTypeSizeInBits(ElementTy) % 8) == 0 &&
  2181. "Only multiple-of-8 sized vector elements are viable");
  2182. ++NumVectorized;
  2183. }
  2184. assert((!IntTy && !VecTy) || (IntTy && !VecTy) || (!IntTy && VecTy));
  2185. }
  2186. bool visit(AllocaSlices::const_iterator I) {
  2187. bool CanSROA = true;
  2188. BeginOffset = I->beginOffset();
  2189. EndOffset = I->endOffset();
  2190. IsSplittable = I->isSplittable();
  2191. IsSplit =
  2192. BeginOffset < NewAllocaBeginOffset || EndOffset > NewAllocaEndOffset;
  2193. DEBUG(dbgs() << " rewriting " << (IsSplit ? "split " : ""));
  2194. DEBUG(AS.printSlice(dbgs(), I, ""));
  2195. DEBUG(dbgs() << "\n");
  2196. // Compute the intersecting offset range.
  2197. assert(BeginOffset < NewAllocaEndOffset);
  2198. assert(EndOffset > NewAllocaBeginOffset);
  2199. NewBeginOffset = std::max(BeginOffset, NewAllocaBeginOffset);
  2200. NewEndOffset = std::min(EndOffset, NewAllocaEndOffset);
  2201. SliceSize = NewEndOffset - NewBeginOffset;
  2202. OldUse = I->getUse();
  2203. OldPtr = cast<Instruction>(OldUse->get());
  2204. Instruction *OldUserI = cast<Instruction>(OldUse->getUser());
  2205. IRB.SetInsertPoint(OldUserI);
  2206. IRB.SetCurrentDebugLocation(OldUserI->getDebugLoc());
  2207. IRB.SetNamePrefix(Twine(NewAI.getName()) + "." + Twine(BeginOffset) + ".");
  2208. CanSROA &= visit(cast<Instruction>(OldUse->getUser()));
  2209. if (VecTy || IntTy)
  2210. assert(CanSROA);
  2211. return CanSROA;
  2212. }
  2213. private:
  2214. // Make sure the other visit overloads are visible.
  2215. using Base::visit;
  2216. // Every instruction which can end up as a user must have a rewrite rule.
  2217. bool visitInstruction(Instruction &I) {
  2218. DEBUG(dbgs() << " !!!! Cannot rewrite: " << I << "\n");
  2219. llvm_unreachable("No rewrite rule for this instruction!");
  2220. }
  2221. Value *getNewAllocaSlicePtr(IRBuilderTy &IRB, Type *PointerTy) {
  2222. // Note that the offset computation can use BeginOffset or NewBeginOffset
  2223. // interchangeably for unsplit slices.
  2224. assert(IsSplit || BeginOffset == NewBeginOffset);
  2225. uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
  2226. #ifndef NDEBUG
  2227. StringRef OldName = OldPtr->getName();
  2228. // Skip through the last '.sroa.' component of the name.
  2229. size_t LastSROAPrefix = OldName.rfind(".sroa.");
  2230. if (LastSROAPrefix != StringRef::npos) {
  2231. OldName = OldName.substr(LastSROAPrefix + strlen(".sroa."));
  2232. // Look for an SROA slice index.
  2233. size_t IndexEnd = OldName.find_first_not_of("0123456789");
  2234. if (IndexEnd != StringRef::npos && OldName[IndexEnd] == '.') {
  2235. // Strip the index and look for the offset.
  2236. OldName = OldName.substr(IndexEnd + 1);
  2237. size_t OffsetEnd = OldName.find_first_not_of("0123456789");
  2238. if (OffsetEnd != StringRef::npos && OldName[OffsetEnd] == '.')
  2239. // Strip the offset.
  2240. OldName = OldName.substr(OffsetEnd + 1);
  2241. }
  2242. }
  2243. // Strip any SROA suffixes as well.
  2244. OldName = OldName.substr(0, OldName.find(".sroa_"));
  2245. #endif
  2246. return getAdjustedPtr(IRB, DL, &NewAI,
  2247. APInt(DL.getPointerSizeInBits(), Offset), PointerTy,
  2248. #ifndef NDEBUG
  2249. Twine(OldName) + "."
  2250. #else
  2251. Twine()
  2252. #endif
  2253. );
  2254. }
  2255. /// \brief Compute suitable alignment to access this slice of the *new*
  2256. /// alloca.
  2257. ///
  2258. /// You can optionally pass a type to this routine and if that type's ABI
  2259. /// alignment is itself suitable, this will return zero.
  2260. unsigned getSliceAlign(Type *Ty = nullptr) {
  2261. unsigned NewAIAlign = NewAI.getAlignment();
  2262. if (!NewAIAlign)
  2263. NewAIAlign = DL.getABITypeAlignment(NewAI.getAllocatedType());
  2264. unsigned Align =
  2265. MinAlign(NewAIAlign, NewBeginOffset - NewAllocaBeginOffset);
  2266. return (Ty && Align == DL.getABITypeAlignment(Ty)) ? 0 : Align;
  2267. }
  2268. unsigned getIndex(uint64_t Offset) {
  2269. assert(VecTy && "Can only call getIndex when rewriting a vector");
  2270. uint64_t RelOffset = Offset - NewAllocaBeginOffset;
  2271. assert(RelOffset / ElementSize < UINT32_MAX && "Index out of bounds");
  2272. uint32_t Index = RelOffset / ElementSize;
  2273. assert(Index * ElementSize == RelOffset);
  2274. return Index;
  2275. }
  2276. void deleteIfTriviallyDead(Value *V) {
  2277. Instruction *I = cast<Instruction>(V);
  2278. if (isInstructionTriviallyDead(I))
  2279. Pass.DeadInsts.insert(I);
  2280. }
  2281. Value *rewriteVectorizedLoadInst() {
  2282. unsigned BeginIndex = getIndex(NewBeginOffset);
  2283. unsigned EndIndex = getIndex(NewEndOffset);
  2284. assert(EndIndex > BeginIndex && "Empty vector!");
  2285. Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
  2286. return extractVector(IRB, V, BeginIndex, EndIndex, "vec");
  2287. }
  2288. Value *rewriteIntegerLoad(LoadInst &LI) {
  2289. assert(IntTy && "We cannot insert an integer to the alloca");
  2290. assert(!LI.isVolatile());
  2291. Value *V = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
  2292. V = convertValue(DL, IRB, V, IntTy);
  2293. assert(NewBeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
  2294. uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
  2295. if (Offset > 0 || NewEndOffset < NewAllocaEndOffset)
  2296. V = extractInteger(DL, IRB, V, cast<IntegerType>(LI.getType()), Offset,
  2297. "extract");
  2298. return V;
  2299. }
  2300. bool visitLoadInst(LoadInst &LI) {
  2301. DEBUG(dbgs() << " original: " << LI << "\n");
  2302. Value *OldOp = LI.getOperand(0);
  2303. assert(OldOp == OldPtr);
  2304. Type *TargetTy = IsSplit ? Type::getIntNTy(LI.getContext(), SliceSize * 8)
  2305. : LI.getType();
  2306. const bool IsLoadPastEnd = DL.getTypeStoreSize(TargetTy) > SliceSize;
  2307. bool IsPtrAdjusted = false;
  2308. Value *V;
  2309. if (VecTy) {
  2310. V = rewriteVectorizedLoadInst();
  2311. } else if (IntTy && LI.getType()->isIntegerTy()) {
  2312. V = rewriteIntegerLoad(LI);
  2313. } else if (NewBeginOffset == NewAllocaBeginOffset &&
  2314. NewEndOffset == NewAllocaEndOffset &&
  2315. (canConvertValue(DL, NewAllocaTy, TargetTy) ||
  2316. (IsLoadPastEnd && NewAllocaTy->isIntegerTy() &&
  2317. TargetTy->isIntegerTy()))) {
  2318. LoadInst *NewLI = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(),
  2319. LI.isVolatile(), LI.getName());
  2320. if (LI.isVolatile())
  2321. NewLI->setAtomic(LI.getOrdering(), LI.getSynchScope());
  2322. V = NewLI;
  2323. // If this is an integer load past the end of the slice (which means the
  2324. // bytes outside the slice are undef or this load is dead) just forcibly
  2325. // fix the integer size with correct handling of endianness.
  2326. if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
  2327. if (auto *TITy = dyn_cast<IntegerType>(TargetTy))
  2328. if (AITy->getBitWidth() < TITy->getBitWidth()) {
  2329. V = IRB.CreateZExt(V, TITy, "load.ext");
  2330. if (DL.isBigEndian())
  2331. V = IRB.CreateShl(V, TITy->getBitWidth() - AITy->getBitWidth(),
  2332. "endian_shift");
  2333. }
  2334. } else {
  2335. Type *LTy = TargetTy->getPointerTo();
  2336. LoadInst *NewLI = IRB.CreateAlignedLoad(getNewAllocaSlicePtr(IRB, LTy),
  2337. getSliceAlign(TargetTy),
  2338. LI.isVolatile(), LI.getName());
  2339. if (LI.isVolatile())
  2340. NewLI->setAtomic(LI.getOrdering(), LI.getSynchScope());
  2341. V = NewLI;
  2342. IsPtrAdjusted = true;
  2343. }
  2344. V = convertValue(DL, IRB, V, TargetTy);
  2345. if (IsSplit) {
  2346. assert(!LI.isVolatile());
  2347. assert(LI.getType()->isIntegerTy() &&
  2348. "Only integer type loads and stores are split");
  2349. assert(SliceSize < DL.getTypeStoreSize(LI.getType()) &&
  2350. "Split load isn't smaller than original load");
  2351. assert(LI.getType()->getIntegerBitWidth() ==
  2352. DL.getTypeStoreSizeInBits(LI.getType()) &&
  2353. "Non-byte-multiple bit width");
  2354. // Move the insertion point just past the load so that we can refer to it.
  2355. IRB.SetInsertPoint(std::next(BasicBlock::iterator(&LI)));
  2356. // Create a placeholder value with the same type as LI to use as the
  2357. // basis for the new value. This allows us to replace the uses of LI with
  2358. // the computed value, and then replace the placeholder with LI, leaving
  2359. // LI only used for this computation.
  2360. Value *Placeholder =
  2361. new LoadInst(UndefValue::get(LI.getType()->getPointerTo()));
  2362. V = insertInteger(DL, IRB, Placeholder, V, NewBeginOffset - BeginOffset,
  2363. "insert");
  2364. LI.replaceAllUsesWith(V);
  2365. Placeholder->replaceAllUsesWith(&LI);
  2366. delete Placeholder;
  2367. } else {
  2368. LI.replaceAllUsesWith(V);
  2369. }
  2370. Pass.DeadInsts.insert(&LI);
  2371. deleteIfTriviallyDead(OldOp);
  2372. DEBUG(dbgs() << " to: " << *V << "\n");
  2373. return !LI.isVolatile() && !IsPtrAdjusted;
  2374. }
  2375. bool rewriteVectorizedStoreInst(Value *V, StoreInst &SI, Value *OldOp) {
  2376. if (V->getType() != VecTy) {
  2377. unsigned BeginIndex = getIndex(NewBeginOffset);
  2378. unsigned EndIndex = getIndex(NewEndOffset);
  2379. assert(EndIndex > BeginIndex && "Empty vector!");
  2380. unsigned NumElements = EndIndex - BeginIndex;
  2381. assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
  2382. Type *SliceTy = (NumElements == 1)
  2383. ? ElementTy
  2384. : VectorType::get(ElementTy, NumElements);
  2385. if (V->getType() != SliceTy)
  2386. V = convertValue(DL, IRB, V, SliceTy);
  2387. // Mix in the existing elements.
  2388. Value *Old = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
  2389. V = insertVector(IRB, Old, V, BeginIndex, "vec");
  2390. }
  2391. StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
  2392. Pass.DeadInsts.insert(&SI);
  2393. (void)Store;
  2394. DEBUG(dbgs() << " to: " << *Store << "\n");
  2395. return true;
  2396. }
  2397. bool rewriteIntegerStore(Value *V, StoreInst &SI) {
  2398. assert(IntTy && "We cannot extract an integer from the alloca");
  2399. assert(!SI.isVolatile());
  2400. if (DL.getTypeSizeInBits(V->getType()) != IntTy->getBitWidth()) {
  2401. Value *Old =
  2402. IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
  2403. Old = convertValue(DL, IRB, Old, IntTy);
  2404. assert(BeginOffset >= NewAllocaBeginOffset && "Out of bounds offset");
  2405. uint64_t Offset = BeginOffset - NewAllocaBeginOffset;
  2406. V = insertInteger(DL, IRB, Old, SI.getValueOperand(), Offset, "insert");
  2407. }
  2408. V = convertValue(DL, IRB, V, NewAllocaTy);
  2409. StoreInst *Store = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment());
  2410. Pass.DeadInsts.insert(&SI);
  2411. (void)Store;
  2412. DEBUG(dbgs() << " to: " << *Store << "\n");
  2413. return true;
  2414. }
  2415. bool visitStoreInst(StoreInst &SI) {
  2416. DEBUG(dbgs() << " original: " << SI << "\n");
  2417. Value *OldOp = SI.getOperand(1);
  2418. assert(OldOp == OldPtr);
  2419. Value *V = SI.getValueOperand();
  2420. // Strip all inbounds GEPs and pointer casts to try to dig out any root
  2421. // alloca that should be re-examined after promoting this alloca.
  2422. if (V->getType()->isPointerTy())
  2423. if (AllocaInst *AI = dyn_cast<AllocaInst>(V->stripInBoundsOffsets()))
  2424. Pass.PostPromotionWorklist.insert(AI);
  2425. if (SliceSize < DL.getTypeStoreSize(V->getType())) {
  2426. assert(!SI.isVolatile());
  2427. assert(V->getType()->isIntegerTy() &&
  2428. "Only integer type loads and stores are split");
  2429. assert(V->getType()->getIntegerBitWidth() ==
  2430. DL.getTypeStoreSizeInBits(V->getType()) &&
  2431. "Non-byte-multiple bit width");
  2432. IntegerType *NarrowTy = Type::getIntNTy(SI.getContext(), SliceSize * 8);
  2433. V = extractInteger(DL, IRB, V, NarrowTy, NewBeginOffset - BeginOffset,
  2434. "extract");
  2435. }
  2436. if (VecTy)
  2437. return rewriteVectorizedStoreInst(V, SI, OldOp);
  2438. if (IntTy && V->getType()->isIntegerTy())
  2439. return rewriteIntegerStore(V, SI);
  2440. const bool IsStorePastEnd = DL.getTypeStoreSize(V->getType()) > SliceSize;
  2441. StoreInst *NewSI;
  2442. if (NewBeginOffset == NewAllocaBeginOffset &&
  2443. NewEndOffset == NewAllocaEndOffset &&
  2444. (canConvertValue(DL, V->getType(), NewAllocaTy) ||
  2445. (IsStorePastEnd && NewAllocaTy->isIntegerTy() &&
  2446. V->getType()->isIntegerTy()))) {
  2447. // If this is an integer store past the end of slice (and thus the bytes
  2448. // past that point are irrelevant or this is unreachable), truncate the
  2449. // value prior to storing.
  2450. if (auto *VITy = dyn_cast<IntegerType>(V->getType()))
  2451. if (auto *AITy = dyn_cast<IntegerType>(NewAllocaTy))
  2452. if (VITy->getBitWidth() > AITy->getBitWidth()) {
  2453. if (DL.isBigEndian())
  2454. V = IRB.CreateLShr(V, VITy->getBitWidth() - AITy->getBitWidth(),
  2455. "endian_shift");
  2456. V = IRB.CreateTrunc(V, AITy, "load.trunc");
  2457. }
  2458. V = convertValue(DL, IRB, V, NewAllocaTy);
  2459. NewSI = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
  2460. SI.isVolatile());
  2461. } else {
  2462. Value *NewPtr = getNewAllocaSlicePtr(IRB, V->getType()->getPointerTo());
  2463. NewSI = IRB.CreateAlignedStore(V, NewPtr, getSliceAlign(V->getType()),
  2464. SI.isVolatile());
  2465. }
  2466. if (SI.isVolatile())
  2467. NewSI->setAtomic(SI.getOrdering(), SI.getSynchScope());
  2468. Pass.DeadInsts.insert(&SI);
  2469. deleteIfTriviallyDead(OldOp);
  2470. DEBUG(dbgs() << " to: " << *NewSI << "\n");
  2471. return NewSI->getPointerOperand() == &NewAI && !SI.isVolatile();
  2472. }
  2473. /// \brief Compute an integer value from splatting an i8 across the given
  2474. /// number of bytes.
  2475. ///
  2476. /// Note that this routine assumes an i8 is a byte. If that isn't true, don't
  2477. /// call this routine.
  2478. /// FIXME: Heed the advice above.
  2479. ///
  2480. /// \param V The i8 value to splat.
  2481. /// \param Size The number of bytes in the output (assuming i8 is one byte)
  2482. Value *getIntegerSplat(Value *V, unsigned Size) {
  2483. assert(Size > 0 && "Expected a positive number of bytes.");
  2484. IntegerType *VTy = cast<IntegerType>(V->getType());
  2485. assert(VTy->getBitWidth() == 8 && "Expected an i8 value for the byte");
  2486. if (Size == 1)
  2487. return V;
  2488. Type *SplatIntTy = Type::getIntNTy(VTy->getContext(), Size * 8);
  2489. V = IRB.CreateMul(
  2490. IRB.CreateZExt(V, SplatIntTy, "zext"),
  2491. ConstantExpr::getUDiv(
  2492. Constant::getAllOnesValue(SplatIntTy),
  2493. ConstantExpr::getZExt(Constant::getAllOnesValue(V->getType()),
  2494. SplatIntTy)),
  2495. "isplat");
  2496. return V;
  2497. }
  2498. /// \brief Compute a vector splat for a given element value.
  2499. Value *getVectorSplat(Value *V, unsigned NumElements) {
  2500. V = IRB.CreateVectorSplat(NumElements, V, "vsplat");
  2501. DEBUG(dbgs() << " splat: " << *V << "\n");
  2502. return V;
  2503. }
  2504. bool visitMemSetInst(MemSetInst &II) {
  2505. DEBUG(dbgs() << " original: " << II << "\n");
  2506. assert(II.getRawDest() == OldPtr);
  2507. // If the memset has a variable size, it cannot be split, just adjust the
  2508. // pointer to the new alloca.
  2509. if (!isa<Constant>(II.getLength())) {
  2510. assert(!IsSplit);
  2511. assert(NewBeginOffset == BeginOffset);
  2512. II.setDest(getNewAllocaSlicePtr(IRB, OldPtr->getType()));
  2513. Type *CstTy = II.getAlignmentCst()->getType();
  2514. II.setAlignment(ConstantInt::get(CstTy, getSliceAlign()));
  2515. deleteIfTriviallyDead(OldPtr);
  2516. return false;
  2517. }
  2518. // Record this instruction for deletion.
  2519. Pass.DeadInsts.insert(&II);
  2520. Type *AllocaTy = NewAI.getAllocatedType();
  2521. Type *ScalarTy = AllocaTy->getScalarType();
  2522. // If this doesn't map cleanly onto the alloca type, and that type isn't
  2523. // a single value type, just emit a memset.
  2524. if (!VecTy && !IntTy &&
  2525. (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
  2526. SliceSize != DL.getTypeStoreSize(AllocaTy) ||
  2527. !AllocaTy->isSingleValueType() ||
  2528. !DL.isLegalInteger(DL.getTypeSizeInBits(ScalarTy)) ||
  2529. DL.getTypeSizeInBits(ScalarTy) % 8 != 0)) {
  2530. Type *SizeTy = II.getLength()->getType();
  2531. Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
  2532. CallInst *New = IRB.CreateMemSet(
  2533. getNewAllocaSlicePtr(IRB, OldPtr->getType()), II.getValue(), Size,
  2534. getSliceAlign(), II.isVolatile());
  2535. (void)New;
  2536. DEBUG(dbgs() << " to: " << *New << "\n");
  2537. return false;
  2538. }
  2539. // If we can represent this as a simple value, we have to build the actual
  2540. // value to store, which requires expanding the byte present in memset to
  2541. // a sensible representation for the alloca type. This is essentially
  2542. // splatting the byte to a sufficiently wide integer, splatting it across
  2543. // any desired vector width, and bitcasting to the final type.
  2544. Value *V;
  2545. if (VecTy) {
  2546. // If this is a memset of a vectorized alloca, insert it.
  2547. assert(ElementTy == ScalarTy);
  2548. unsigned BeginIndex = getIndex(NewBeginOffset);
  2549. unsigned EndIndex = getIndex(NewEndOffset);
  2550. assert(EndIndex > BeginIndex && "Empty vector!");
  2551. unsigned NumElements = EndIndex - BeginIndex;
  2552. assert(NumElements <= VecTy->getNumElements() && "Too many elements!");
  2553. Value *Splat =
  2554. getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ElementTy) / 8);
  2555. Splat = convertValue(DL, IRB, Splat, ElementTy);
  2556. if (NumElements > 1)
  2557. Splat = getVectorSplat(Splat, NumElements);
  2558. Value *Old =
  2559. IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
  2560. V = insertVector(IRB, Old, Splat, BeginIndex, "vec");
  2561. } else if (IntTy) {
  2562. // If this is a memset on an alloca where we can widen stores, insert the
  2563. // set integer.
  2564. assert(!II.isVolatile());
  2565. uint64_t Size = NewEndOffset - NewBeginOffset;
  2566. V = getIntegerSplat(II.getValue(), Size);
  2567. if (IntTy && (BeginOffset != NewAllocaBeginOffset ||
  2568. EndOffset != NewAllocaBeginOffset)) {
  2569. Value *Old =
  2570. IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
  2571. Old = convertValue(DL, IRB, Old, IntTy);
  2572. uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
  2573. V = insertInteger(DL, IRB, Old, V, Offset, "insert");
  2574. } else {
  2575. assert(V->getType() == IntTy &&
  2576. "Wrong type for an alloca wide integer!");
  2577. }
  2578. V = convertValue(DL, IRB, V, AllocaTy);
  2579. } else {
  2580. // Established these invariants above.
  2581. assert(NewBeginOffset == NewAllocaBeginOffset);
  2582. assert(NewEndOffset == NewAllocaEndOffset);
  2583. V = getIntegerSplat(II.getValue(), DL.getTypeSizeInBits(ScalarTy) / 8);
  2584. if (VectorType *AllocaVecTy = dyn_cast<VectorType>(AllocaTy))
  2585. V = getVectorSplat(V, AllocaVecTy->getNumElements());
  2586. V = convertValue(DL, IRB, V, AllocaTy);
  2587. }
  2588. Value *New = IRB.CreateAlignedStore(V, &NewAI, NewAI.getAlignment(),
  2589. II.isVolatile());
  2590. (void)New;
  2591. DEBUG(dbgs() << " to: " << *New << "\n");
  2592. return !II.isVolatile();
  2593. }
  2594. bool visitMemTransferInst(MemTransferInst &II) {
  2595. // Rewriting of memory transfer instructions can be a bit tricky. We break
  2596. // them into two categories: split intrinsics and unsplit intrinsics.
  2597. DEBUG(dbgs() << " original: " << II << "\n");
  2598. bool IsDest = &II.getRawDestUse() == OldUse;
  2599. assert((IsDest && II.getRawDest() == OldPtr) ||
  2600. (!IsDest && II.getRawSource() == OldPtr));
  2601. unsigned SliceAlign = getSliceAlign();
  2602. // For unsplit intrinsics, we simply modify the source and destination
  2603. // pointers in place. This isn't just an optimization, it is a matter of
  2604. // correctness. With unsplit intrinsics we may be dealing with transfers
  2605. // within a single alloca before SROA ran, or with transfers that have
  2606. // a variable length. We may also be dealing with memmove instead of
  2607. // memcpy, and so simply updating the pointers is the necessary for us to
  2608. // update both source and dest of a single call.
  2609. if (!IsSplittable) {
  2610. Value *AdjustedPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
  2611. if (IsDest)
  2612. II.setDest(AdjustedPtr);
  2613. else
  2614. II.setSource(AdjustedPtr);
  2615. if (II.getAlignment() > SliceAlign) {
  2616. Type *CstTy = II.getAlignmentCst()->getType();
  2617. II.setAlignment(
  2618. ConstantInt::get(CstTy, MinAlign(II.getAlignment(), SliceAlign)));
  2619. }
  2620. DEBUG(dbgs() << " to: " << II << "\n");
  2621. deleteIfTriviallyDead(OldPtr);
  2622. return false;
  2623. }
  2624. // For split transfer intrinsics we have an incredibly useful assurance:
  2625. // the source and destination do not reside within the same alloca, and at
  2626. // least one of them does not escape. This means that we can replace
  2627. // memmove with memcpy, and we don't need to worry about all manner of
  2628. // downsides to splitting and transforming the operations.
  2629. // If this doesn't map cleanly onto the alloca type, and that type isn't
  2630. // a single value type, just emit a memcpy.
  2631. bool EmitMemCpy =
  2632. !VecTy && !IntTy &&
  2633. (BeginOffset > NewAllocaBeginOffset || EndOffset < NewAllocaEndOffset ||
  2634. SliceSize != DL.getTypeStoreSize(NewAI.getAllocatedType()) ||
  2635. !NewAI.getAllocatedType()->isSingleValueType());
  2636. // If we're just going to emit a memcpy, the alloca hasn't changed, and the
  2637. // size hasn't been shrunk based on analysis of the viable range, this is
  2638. // a no-op.
  2639. if (EmitMemCpy && &OldAI == &NewAI) {
  2640. // Ensure the start lines up.
  2641. assert(NewBeginOffset == BeginOffset);
  2642. // Rewrite the size as needed.
  2643. if (NewEndOffset != EndOffset)
  2644. II.setLength(ConstantInt::get(II.getLength()->getType(),
  2645. NewEndOffset - NewBeginOffset));
  2646. return false;
  2647. }
  2648. // Record this instruction for deletion.
  2649. Pass.DeadInsts.insert(&II);
  2650. // Strip all inbounds GEPs and pointer casts to try to dig out any root
  2651. // alloca that should be re-examined after rewriting this instruction.
  2652. Value *OtherPtr = IsDest ? II.getRawSource() : II.getRawDest();
  2653. if (AllocaInst *AI =
  2654. dyn_cast<AllocaInst>(OtherPtr->stripInBoundsOffsets())) {
  2655. assert(AI != &OldAI && AI != &NewAI &&
  2656. "Splittable transfers cannot reach the same alloca on both ends.");
  2657. Pass.Worklist.insert(AI);
  2658. }
  2659. Type *OtherPtrTy = OtherPtr->getType();
  2660. unsigned OtherAS = OtherPtrTy->getPointerAddressSpace();
  2661. // Compute the relative offset for the other pointer within the transfer.
  2662. unsigned IntPtrWidth = DL.getPointerSizeInBits(OtherAS);
  2663. APInt OtherOffset(IntPtrWidth, NewBeginOffset - BeginOffset);
  2664. unsigned OtherAlign = MinAlign(II.getAlignment() ? II.getAlignment() : 1,
  2665. OtherOffset.zextOrTrunc(64).getZExtValue());
  2666. if (EmitMemCpy) {
  2667. // Compute the other pointer, folding as much as possible to produce
  2668. // a single, simple GEP in most cases.
  2669. OtherPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
  2670. OtherPtr->getName() + ".");
  2671. Value *OurPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
  2672. Type *SizeTy = II.getLength()->getType();
  2673. Constant *Size = ConstantInt::get(SizeTy, NewEndOffset - NewBeginOffset);
  2674. CallInst *New = IRB.CreateMemCpy(
  2675. IsDest ? OurPtr : OtherPtr, IsDest ? OtherPtr : OurPtr, Size,
  2676. MinAlign(SliceAlign, OtherAlign), II.isVolatile());
  2677. (void)New;
  2678. DEBUG(dbgs() << " to: " << *New << "\n");
  2679. return false;
  2680. }
  2681. bool IsWholeAlloca = NewBeginOffset == NewAllocaBeginOffset &&
  2682. NewEndOffset == NewAllocaEndOffset;
  2683. uint64_t Size = NewEndOffset - NewBeginOffset;
  2684. unsigned BeginIndex = VecTy ? getIndex(NewBeginOffset) : 0;
  2685. unsigned EndIndex = VecTy ? getIndex(NewEndOffset) : 0;
  2686. unsigned NumElements = EndIndex - BeginIndex;
  2687. IntegerType *SubIntTy =
  2688. IntTy ? Type::getIntNTy(IntTy->getContext(), Size * 8) : nullptr;
  2689. // Reset the other pointer type to match the register type we're going to
  2690. // use, but using the address space of the original other pointer.
  2691. if (VecTy && !IsWholeAlloca) {
  2692. if (NumElements == 1)
  2693. OtherPtrTy = VecTy->getElementType();
  2694. else
  2695. OtherPtrTy = VectorType::get(VecTy->getElementType(), NumElements);
  2696. OtherPtrTy = OtherPtrTy->getPointerTo(OtherAS);
  2697. } else if (IntTy && !IsWholeAlloca) {
  2698. OtherPtrTy = SubIntTy->getPointerTo(OtherAS);
  2699. } else {
  2700. OtherPtrTy = NewAllocaTy->getPointerTo(OtherAS);
  2701. }
  2702. Value *SrcPtr = getAdjustedPtr(IRB, DL, OtherPtr, OtherOffset, OtherPtrTy,
  2703. OtherPtr->getName() + ".");
  2704. unsigned SrcAlign = OtherAlign;
  2705. Value *DstPtr = &NewAI;
  2706. unsigned DstAlign = SliceAlign;
  2707. if (!IsDest) {
  2708. std::swap(SrcPtr, DstPtr);
  2709. std::swap(SrcAlign, DstAlign);
  2710. }
  2711. Value *Src;
  2712. if (VecTy && !IsWholeAlloca && !IsDest) {
  2713. Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
  2714. Src = extractVector(IRB, Src, BeginIndex, EndIndex, "vec");
  2715. } else if (IntTy && !IsWholeAlloca && !IsDest) {
  2716. Src = IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "load");
  2717. Src = convertValue(DL, IRB, Src, IntTy);
  2718. uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
  2719. Src = extractInteger(DL, IRB, Src, SubIntTy, Offset, "extract");
  2720. } else {
  2721. Src =
  2722. IRB.CreateAlignedLoad(SrcPtr, SrcAlign, II.isVolatile(), "copyload");
  2723. }
  2724. if (VecTy && !IsWholeAlloca && IsDest) {
  2725. Value *Old =
  2726. IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
  2727. Src = insertVector(IRB, Old, Src, BeginIndex, "vec");
  2728. } else if (IntTy && !IsWholeAlloca && IsDest) {
  2729. Value *Old =
  2730. IRB.CreateAlignedLoad(&NewAI, NewAI.getAlignment(), "oldload");
  2731. Old = convertValue(DL, IRB, Old, IntTy);
  2732. uint64_t Offset = NewBeginOffset - NewAllocaBeginOffset;
  2733. Src = insertInteger(DL, IRB, Old, Src, Offset, "insert");
  2734. Src = convertValue(DL, IRB, Src, NewAllocaTy);
  2735. }
  2736. StoreInst *Store = cast<StoreInst>(
  2737. IRB.CreateAlignedStore(Src, DstPtr, DstAlign, II.isVolatile()));
  2738. (void)Store;
  2739. DEBUG(dbgs() << " to: " << *Store << "\n");
  2740. return !II.isVolatile();
  2741. }
  2742. bool visitIntrinsicInst(IntrinsicInst &II) {
  2743. assert(II.getIntrinsicID() == Intrinsic::lifetime_start ||
  2744. II.getIntrinsicID() == Intrinsic::lifetime_end);
  2745. DEBUG(dbgs() << " original: " << II << "\n");
  2746. assert(II.getArgOperand(1) == OldPtr);
  2747. // Record this instruction for deletion.
  2748. Pass.DeadInsts.insert(&II);
  2749. ConstantInt *Size =
  2750. ConstantInt::get(cast<IntegerType>(II.getArgOperand(0)->getType()),
  2751. NewEndOffset - NewBeginOffset);
  2752. Value *Ptr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
  2753. Value *New;
  2754. if (II.getIntrinsicID() == Intrinsic::lifetime_start)
  2755. New = IRB.CreateLifetimeStart(Ptr, Size);
  2756. else
  2757. New = IRB.CreateLifetimeEnd(Ptr, Size);
  2758. (void)New;
  2759. DEBUG(dbgs() << " to: " << *New << "\n");
  2760. return true;
  2761. }
  2762. bool visitPHINode(PHINode &PN) {
  2763. DEBUG(dbgs() << " original: " << PN << "\n");
  2764. assert(BeginOffset >= NewAllocaBeginOffset && "PHIs are unsplittable");
  2765. assert(EndOffset <= NewAllocaEndOffset && "PHIs are unsplittable");
  2766. // We would like to compute a new pointer in only one place, but have it be
  2767. // as local as possible to the PHI. To do that, we re-use the location of
  2768. // the old pointer, which necessarily must be in the right position to
  2769. // dominate the PHI.
  2770. IRBuilderTy PtrBuilder(IRB);
  2771. if (isa<PHINode>(OldPtr))
  2772. PtrBuilder.SetInsertPoint(OldPtr->getParent()->getFirstInsertionPt());
  2773. else
  2774. PtrBuilder.SetInsertPoint(OldPtr);
  2775. PtrBuilder.SetCurrentDebugLocation(OldPtr->getDebugLoc());
  2776. Value *NewPtr = getNewAllocaSlicePtr(PtrBuilder, OldPtr->getType());
  2777. // Replace the operands which were using the old pointer.
  2778. std::replace(PN.op_begin(), PN.op_end(), cast<Value>(OldPtr), NewPtr);
  2779. DEBUG(dbgs() << " to: " << PN << "\n");
  2780. deleteIfTriviallyDead(OldPtr);
  2781. // PHIs can't be promoted on their own, but often can be speculated. We
  2782. // check the speculation outside of the rewriter so that we see the
  2783. // fully-rewritten alloca.
  2784. PHIUsers.insert(&PN);
  2785. return true;
  2786. }
  2787. bool visitSelectInst(SelectInst &SI) {
  2788. DEBUG(dbgs() << " original: " << SI << "\n");
  2789. assert((SI.getTrueValue() == OldPtr || SI.getFalseValue() == OldPtr) &&
  2790. "Pointer isn't an operand!");
  2791. assert(BeginOffset >= NewAllocaBeginOffset && "Selects are unsplittable");
  2792. assert(EndOffset <= NewAllocaEndOffset && "Selects are unsplittable");
  2793. Value *NewPtr = getNewAllocaSlicePtr(IRB, OldPtr->getType());
  2794. // Replace the operands which were using the old pointer.
  2795. if (SI.getOperand(1) == OldPtr)
  2796. SI.setOperand(1, NewPtr);
  2797. if (SI.getOperand(2) == OldPtr)
  2798. SI.setOperand(2, NewPtr);
  2799. DEBUG(dbgs() << " to: " << SI << "\n");
  2800. deleteIfTriviallyDead(OldPtr);
  2801. // Selects can't be promoted on their own, but often can be speculated. We
  2802. // check the speculation outside of the rewriter so that we see the
  2803. // fully-rewritten alloca.
  2804. SelectUsers.insert(&SI);
  2805. return true;
  2806. }
  2807. };
  2808. }
  2809. namespace {
  2810. /// \brief Visitor to rewrite aggregate loads and stores as scalar.
  2811. ///
  2812. /// This pass aggressively rewrites all aggregate loads and stores on
  2813. /// a particular pointer (or any pointer derived from it which we can identify)
  2814. /// with scalar loads and stores.
  2815. class AggLoadStoreRewriter : public InstVisitor<AggLoadStoreRewriter, bool> {
  2816. // Befriend the base class so it can delegate to private visit methods.
  2817. friend class llvm::InstVisitor<AggLoadStoreRewriter, bool>;
  2818. const DataLayout &DL;
  2819. const bool SkipHLSLMat; // HLSL Change - not sroa matrix type.
  2820. /// Queue of pointer uses to analyze and potentially rewrite.
  2821. SmallVector<Use *, 8> Queue;
  2822. /// Set to prevent us from cycling with phi nodes and loops.
  2823. SmallPtrSet<User *, 8> Visited;
  2824. /// The current pointer use being rewritten. This is used to dig up the used
  2825. /// value (as opposed to the user).
  2826. Use *U;
  2827. public:
  2828. AggLoadStoreRewriter(const DataLayout &DL, const bool SkipHLSLMat)
  2829. // HLSL Change - not sroa matrix type.
  2830. : DL(DL), SkipHLSLMat(SkipHLSLMat) {}
  2831. /// Rewrite loads and stores through a pointer and all pointers derived from
  2832. /// it.
  2833. bool rewrite(Instruction &I) {
  2834. DEBUG(dbgs() << " Rewriting FCA loads and stores...\n");
  2835. enqueueUsers(I);
  2836. bool Changed = false;
  2837. while (!Queue.empty()) {
  2838. U = Queue.pop_back_val();
  2839. Changed |= visit(cast<Instruction>(U->getUser()));
  2840. }
  2841. return Changed;
  2842. }
  2843. private:
  2844. /// Enqueue all the users of the given instruction for further processing.
  2845. /// This uses a set to de-duplicate users.
  2846. void enqueueUsers(Instruction &I) {
  2847. for (Use &U : I.uses())
  2848. if (Visited.insert(U.getUser()).second)
  2849. Queue.push_back(&U);
  2850. }
  2851. // Conservative default is to not rewrite anything.
  2852. bool visitInstruction(Instruction &I) { return false; }
  2853. /// \brief Generic recursive split emission class.
  2854. template <typename Derived> class OpSplitter {
  2855. protected:
  2856. /// The builder used to form new instructions.
  2857. IRBuilderTy IRB;
  2858. /// The indices which to be used with insert- or extractvalue to select the
  2859. /// appropriate value within the aggregate.
  2860. SmallVector<unsigned, 4> Indices;
  2861. /// The indices to a GEP instruction which will move Ptr to the correct slot
  2862. /// within the aggregate.
  2863. SmallVector<Value *, 4> GEPIndices;
  2864. /// The base pointer of the original op, used as a base for GEPing the
  2865. /// split operations.
  2866. Value *Ptr;
  2867. /// Initialize the splitter with an insertion point, Ptr and start with a
  2868. /// single zero GEP index.
  2869. OpSplitter(Instruction *InsertionPoint, Value *Ptr)
  2870. : IRB(InsertionPoint), GEPIndices(1, IRB.getInt32(0)), Ptr(Ptr) {}
  2871. public:
  2872. /// \brief Generic recursive split emission routine.
  2873. ///
  2874. /// This method recursively splits an aggregate op (load or store) into
  2875. /// scalar or vector ops. It splits recursively until it hits a single value
  2876. /// and emits that single value operation via the template argument.
  2877. ///
  2878. /// The logic of this routine relies on GEPs and insertvalue and
  2879. /// extractvalue all operating with the same fundamental index list, merely
  2880. /// formatted differently (GEPs need actual values).
  2881. ///
  2882. /// \param Ty The type being split recursively into smaller ops.
  2883. /// \param Agg The aggregate value being built up or stored, depending on
  2884. /// whether this is splitting a load or a store respectively.
  2885. void emitSplitOps(Type *Ty, Value *&Agg, const Twine &Name) {
  2886. if (Ty->isSingleValueType())
  2887. return static_cast<Derived *>(this)->emitFunc(Ty, Agg, Name);
  2888. if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
  2889. unsigned OldSize = Indices.size();
  2890. (void)OldSize;
  2891. for (unsigned Idx = 0, Size = ATy->getNumElements(); Idx != Size;
  2892. ++Idx) {
  2893. assert(Indices.size() == OldSize && "Did not return to the old size");
  2894. Indices.push_back(Idx);
  2895. GEPIndices.push_back(IRB.getInt32(Idx));
  2896. emitSplitOps(ATy->getElementType(), Agg, Name + "." + Twine(Idx));
  2897. GEPIndices.pop_back();
  2898. Indices.pop_back();
  2899. }
  2900. return;
  2901. }
  2902. if (StructType *STy = dyn_cast<StructType>(Ty)) {
  2903. unsigned OldSize = Indices.size();
  2904. (void)OldSize;
  2905. for (unsigned Idx = 0, Size = STy->getNumElements(); Idx != Size;
  2906. ++Idx) {
  2907. assert(Indices.size() == OldSize && "Did not return to the old size");
  2908. Indices.push_back(Idx);
  2909. GEPIndices.push_back(IRB.getInt32(Idx));
  2910. emitSplitOps(STy->getElementType(Idx), Agg, Name + "." + Twine(Idx));
  2911. GEPIndices.pop_back();
  2912. Indices.pop_back();
  2913. }
  2914. return;
  2915. }
  2916. llvm_unreachable("Only arrays and structs are aggregate loadable types");
  2917. }
  2918. };
  2919. struct LoadOpSplitter : public OpSplitter<LoadOpSplitter> {
  2920. LoadOpSplitter(Instruction *InsertionPoint, Value *Ptr)
  2921. : OpSplitter<LoadOpSplitter>(InsertionPoint, Ptr) {}
  2922. /// Emit a leaf load of a single value. This is called at the leaves of the
  2923. /// recursive emission to actually load values.
  2924. void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
  2925. assert(Ty->isSingleValueType());
  2926. // Load the single value and insert it using the indices.
  2927. Value *GEP =
  2928. IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep");
  2929. Value *Load = IRB.CreateLoad(GEP, Name + ".load");
  2930. Agg = IRB.CreateInsertValue(Agg, Load, Indices, Name + ".insert");
  2931. DEBUG(dbgs() << " to: " << *Load << "\n");
  2932. }
  2933. };
  2934. bool visitLoadInst(LoadInst &LI) {
  2935. assert(LI.getPointerOperand() == *U);
  2936. if (!LI.isSimple() || LI.getType()->isSingleValueType())
  2937. return false;
  2938. // HLSL Change Begin - not sroa matrix type.
  2939. if ((SkipHLSLMat && hlsl::dxilutil::IsHLSLMatrixType(LI.getType())) ||
  2940. hlsl::dxilutil::IsHLSLObjectType(LI.getType()))
  2941. return false;
  2942. // HLSL Change End.
  2943. // We have an aggregate being loaded, split it apart.
  2944. DEBUG(dbgs() << " original: " << LI << "\n");
  2945. LoadOpSplitter Splitter(&LI, *U);
  2946. Value *V = UndefValue::get(LI.getType());
  2947. Splitter.emitSplitOps(LI.getType(), V, LI.getName() + ".fca");
  2948. LI.replaceAllUsesWith(V);
  2949. LI.eraseFromParent();
  2950. return true;
  2951. }
  2952. struct StoreOpSplitter : public OpSplitter<StoreOpSplitter> {
  2953. StoreOpSplitter(Instruction *InsertionPoint, Value *Ptr)
  2954. : OpSplitter<StoreOpSplitter>(InsertionPoint, Ptr) {}
  2955. /// Emit a leaf store of a single value. This is called at the leaves of the
  2956. /// recursive emission to actually produce stores.
  2957. void emitFunc(Type *Ty, Value *&Agg, const Twine &Name) {
  2958. assert(Ty->isSingleValueType());
  2959. // Extract the single value and store it using the indices.
  2960. Value *Store = IRB.CreateStore(
  2961. IRB.CreateExtractValue(Agg, Indices, Name + ".extract"),
  2962. IRB.CreateInBoundsGEP(nullptr, Ptr, GEPIndices, Name + ".gep"));
  2963. (void)Store;
  2964. DEBUG(dbgs() << " to: " << *Store << "\n");
  2965. }
  2966. };
  2967. bool visitStoreInst(StoreInst &SI) {
  2968. if (!SI.isSimple() || SI.getPointerOperand() != *U)
  2969. return false;
  2970. Value *V = SI.getValueOperand();
  2971. if (V->getType()->isSingleValueType())
  2972. return false;
  2973. // HLSL Change Begin - not sroa matrix type.
  2974. if ((SkipHLSLMat && hlsl::dxilutil::IsHLSLMatrixType(V->getType())) ||
  2975. hlsl::dxilutil::IsHLSLObjectType(V->getType()))
  2976. return false;
  2977. // HLSL Change End.
  2978. // We have an aggregate being stored, split it apart.
  2979. DEBUG(dbgs() << " original: " << SI << "\n");
  2980. StoreOpSplitter Splitter(&SI, *U);
  2981. Splitter.emitSplitOps(V->getType(), V, V->getName() + ".fca");
  2982. SI.eraseFromParent();
  2983. return true;
  2984. }
  2985. bool visitBitCastInst(BitCastInst &BC) {
  2986. // HLSL Change Begin - not sroa matrix type.
  2987. if (PointerType *PT = dyn_cast<PointerType>(BC.getType())) {
  2988. Type *EltTy = PT->getElementType();
  2989. if ((SkipHLSLMat && hlsl::dxilutil::IsHLSLMatrixType(EltTy)) ||
  2990. hlsl::dxilutil::IsHLSLObjectType(EltTy))
  2991. return false;
  2992. if (PointerType *SrcPT = dyn_cast<PointerType>(BC.getSrcTy())) {
  2993. Type *SrcEltTy = SrcPT->getElementType();
  2994. if ((SkipHLSLMat && hlsl::dxilutil::IsHLSLMatrixType(SrcEltTy)) ||
  2995. hlsl::dxilutil::IsHLSLObjectType(SrcEltTy))
  2996. return false;
  2997. }
  2998. }
  2999. // HLSL Change End.
  3000. enqueueUsers(BC);
  3001. return false;
  3002. }
  3003. bool visitGetElementPtrInst(GetElementPtrInst &GEPI) {
  3004. enqueueUsers(GEPI);
  3005. return false;
  3006. }
  3007. bool visitPHINode(PHINode &PN) {
  3008. enqueueUsers(PN);
  3009. return false;
  3010. }
  3011. bool visitSelectInst(SelectInst &SI) {
  3012. enqueueUsers(SI);
  3013. return false;
  3014. }
  3015. };
  3016. }
  3017. /// \brief Strip aggregate type wrapping.
  3018. ///
  3019. /// This removes no-op aggregate types wrapping an underlying type. It will
  3020. /// strip as many layers of types as it can without changing either the type
  3021. /// size or the allocated size.
  3022. static Type *stripAggregateTypeWrapping(const DataLayout &DL, Type *Ty) {
  3023. if (Ty->isSingleValueType())
  3024. return Ty;
  3025. uint64_t AllocSize = DL.getTypeAllocSize(Ty);
  3026. uint64_t TypeSize = DL.getTypeSizeInBits(Ty);
  3027. Type *InnerTy;
  3028. if (ArrayType *ArrTy = dyn_cast<ArrayType>(Ty)) {
  3029. InnerTy = ArrTy->getElementType();
  3030. } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
  3031. const StructLayout *SL = DL.getStructLayout(STy);
  3032. unsigned Index = SL->getElementContainingOffset(0);
  3033. InnerTy = STy->getElementType(Index);
  3034. } else {
  3035. return Ty;
  3036. }
  3037. if (AllocSize > DL.getTypeAllocSize(InnerTy) ||
  3038. TypeSize > DL.getTypeSizeInBits(InnerTy))
  3039. return Ty;
  3040. return stripAggregateTypeWrapping(DL, InnerTy);
  3041. }
  3042. /// \brief Try to find a partition of the aggregate type passed in for a given
  3043. /// offset and size.
  3044. ///
  3045. /// This recurses through the aggregate type and tries to compute a subtype
  3046. /// based on the offset and size. When the offset and size span a sub-section
  3047. /// of an array, it will even compute a new array type for that sub-section,
  3048. /// and the same for structs.
  3049. ///
  3050. /// Note that this routine is very strict and tries to find a partition of the
  3051. /// type which produces the *exact* right offset and size. It is not forgiving
  3052. /// when the size or offset cause either end of type-based partition to be off.
  3053. /// Also, this is a best-effort routine. It is reasonable to give up and not
  3054. /// return a type if necessary.
  3055. static Type *getTypePartition(const DataLayout &DL, Type *Ty, uint64_t Offset,
  3056. uint64_t Size) {
  3057. if (Offset == 0 && DL.getTypeAllocSize(Ty) == Size)
  3058. return stripAggregateTypeWrapping(DL, Ty);
  3059. if (Offset > DL.getTypeAllocSize(Ty) ||
  3060. (DL.getTypeAllocSize(Ty) - Offset) < Size)
  3061. return nullptr;
  3062. if (SequentialType *SeqTy = dyn_cast<SequentialType>(Ty)) {
  3063. // We can't partition pointers...
  3064. if (SeqTy->isPointerTy())
  3065. return nullptr;
  3066. Type *ElementTy = SeqTy->getElementType();
  3067. uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
  3068. uint64_t NumSkippedElements = Offset / ElementSize;
  3069. if (ArrayType *ArrTy = dyn_cast<ArrayType>(SeqTy)) {
  3070. if (NumSkippedElements >= ArrTy->getNumElements())
  3071. return nullptr;
  3072. } else if (VectorType *VecTy = dyn_cast<VectorType>(SeqTy)) {
  3073. if (NumSkippedElements >= VecTy->getNumElements())
  3074. return nullptr;
  3075. }
  3076. Offset -= NumSkippedElements * ElementSize;
  3077. // First check if we need to recurse.
  3078. if (Offset > 0 || Size < ElementSize) {
  3079. // Bail if the partition ends in a different array element.
  3080. if ((Offset + Size) > ElementSize)
  3081. return nullptr;
  3082. // Recurse through the element type trying to peel off offset bytes.
  3083. return getTypePartition(DL, ElementTy, Offset, Size);
  3084. }
  3085. assert(Offset == 0);
  3086. if (Size == ElementSize)
  3087. return stripAggregateTypeWrapping(DL, ElementTy);
  3088. assert(Size > ElementSize);
  3089. uint64_t NumElements = Size / ElementSize;
  3090. if (NumElements * ElementSize != Size)
  3091. return nullptr;
  3092. return ArrayType::get(ElementTy, NumElements);
  3093. }
  3094. StructType *STy = dyn_cast<StructType>(Ty);
  3095. if (!STy)
  3096. return nullptr;
  3097. const StructLayout *SL = DL.getStructLayout(STy);
  3098. if (Offset >= SL->getSizeInBytes())
  3099. return nullptr;
  3100. uint64_t EndOffset = Offset + Size;
  3101. if (EndOffset > SL->getSizeInBytes())
  3102. return nullptr;
  3103. unsigned Index = SL->getElementContainingOffset(Offset);
  3104. Offset -= SL->getElementOffset(Index);
  3105. Type *ElementTy = STy->getElementType(Index);
  3106. uint64_t ElementSize = DL.getTypeAllocSize(ElementTy);
  3107. if (Offset >= ElementSize)
  3108. return nullptr; // The offset points into alignment padding.
  3109. // See if any partition must be contained by the element.
  3110. if (Offset > 0 || Size < ElementSize) {
  3111. if ((Offset + Size) > ElementSize)
  3112. return nullptr;
  3113. return getTypePartition(DL, ElementTy, Offset, Size);
  3114. }
  3115. assert(Offset == 0);
  3116. if (Size == ElementSize)
  3117. return stripAggregateTypeWrapping(DL, ElementTy);
  3118. StructType::element_iterator EI = STy->element_begin() + Index,
  3119. EE = STy->element_end();
  3120. if (EndOffset < SL->getSizeInBytes()) {
  3121. unsigned EndIndex = SL->getElementContainingOffset(EndOffset);
  3122. if (Index == EndIndex)
  3123. return nullptr; // Within a single element and its padding.
  3124. // Don't try to form "natural" types if the elements don't line up with the
  3125. // expected size.
  3126. // FIXME: We could potentially recurse down through the last element in the
  3127. // sub-struct to find a natural end point.
  3128. if (SL->getElementOffset(EndIndex) != EndOffset)
  3129. return nullptr;
  3130. assert(Index < EndIndex);
  3131. EE = STy->element_begin() + EndIndex;
  3132. }
  3133. // Try to build up a sub-structure.
  3134. StructType *SubTy =
  3135. StructType::get(STy->getContext(), makeArrayRef(EI, EE), STy->isPacked());
  3136. const StructLayout *SubSL = DL.getStructLayout(SubTy);
  3137. if (Size != SubSL->getSizeInBytes())
  3138. return nullptr; // The sub-struct doesn't have quite the size needed.
  3139. return SubTy;
  3140. }
  3141. /// \brief Pre-split loads and stores to simplify rewriting.
  3142. ///
  3143. /// We want to break up the splittable load+store pairs as much as
  3144. /// possible. This is important to do as a preprocessing step, as once we
  3145. /// start rewriting the accesses to partitions of the alloca we lose the
  3146. /// necessary information to correctly split apart paired loads and stores
  3147. /// which both point into this alloca. The case to consider is something like
  3148. /// the following:
  3149. ///
  3150. /// %a = alloca [12 x i8]
  3151. /// %gep1 = getelementptr [12 x i8]* %a, i32 0, i32 0
  3152. /// %gep2 = getelementptr [12 x i8]* %a, i32 0, i32 4
  3153. /// %gep3 = getelementptr [12 x i8]* %a, i32 0, i32 8
  3154. /// %iptr1 = bitcast i8* %gep1 to i64*
  3155. /// %iptr2 = bitcast i8* %gep2 to i64*
  3156. /// %fptr1 = bitcast i8* %gep1 to float*
  3157. /// %fptr2 = bitcast i8* %gep2 to float*
  3158. /// %fptr3 = bitcast i8* %gep3 to float*
  3159. /// store float 0.0, float* %fptr1
  3160. /// store float 1.0, float* %fptr2
  3161. /// %v = load i64* %iptr1
  3162. /// store i64 %v, i64* %iptr2
  3163. /// %f1 = load float* %fptr2
  3164. /// %f2 = load float* %fptr3
  3165. ///
  3166. /// Here we want to form 3 partitions of the alloca, each 4 bytes large, and
  3167. /// promote everything so we recover the 2 SSA values that should have been
  3168. /// there all along.
  3169. ///
  3170. /// \returns true if any changes are made.
  3171. bool SROA::presplitLoadsAndStores(AllocaInst &AI, AllocaSlices &AS) {
  3172. DEBUG(dbgs() << "Pre-splitting loads and stores\n");
  3173. // Track the loads and stores which are candidates for pre-splitting here, in
  3174. // the order they first appear during the partition scan. These give stable
  3175. // iteration order and a basis for tracking which loads and stores we
  3176. // actually split.
  3177. SmallVector<LoadInst *, 4> Loads;
  3178. SmallVector<StoreInst *, 4> Stores;
  3179. // We need to accumulate the splits required of each load or store where we
  3180. // can find them via a direct lookup. This is important to cross-check loads
  3181. // and stores against each other. We also track the slice so that we can kill
  3182. // all the slices that end up split.
  3183. struct SplitOffsets {
  3184. Slice *S;
  3185. std::vector<uint64_t> Splits;
  3186. };
  3187. SmallDenseMap<Instruction *, SplitOffsets, 8> SplitOffsetsMap;
  3188. // Track loads out of this alloca which cannot, for any reason, be pre-split.
  3189. // This is important as we also cannot pre-split stores of those loads!
  3190. // FIXME: This is all pretty gross. It means that we can be more aggressive
  3191. // in pre-splitting when the load feeding the store happens to come from
  3192. // a separate alloca. Put another way, the effectiveness of SROA would be
  3193. // decreased by a frontend which just concatenated all of its local allocas
  3194. // into one big flat alloca. But defeating such patterns is exactly the job
  3195. // SROA is tasked with! Sadly, to not have this discrepancy we would have
  3196. // change store pre-splitting to actually force pre-splitting of the load
  3197. // that feeds it *and all stores*. That makes pre-splitting much harder, but
  3198. // maybe it would make it more principled?
  3199. SmallPtrSet<LoadInst *, 8> UnsplittableLoads;
  3200. DEBUG(dbgs() << " Searching for candidate loads and stores\n");
  3201. for (auto &P : AS.partitions()) {
  3202. for (Slice &S : P) {
  3203. Instruction *I = cast<Instruction>(S.getUse()->getUser());
  3204. if (!S.isSplittable() ||S.endOffset() <= P.endOffset()) {
  3205. // If this was a load we have to track that it can't participate in any
  3206. // pre-splitting!
  3207. if (auto *LI = dyn_cast<LoadInst>(I))
  3208. UnsplittableLoads.insert(LI);
  3209. continue;
  3210. }
  3211. assert(P.endOffset() > S.beginOffset() &&
  3212. "Empty or backwards partition!");
  3213. // Determine if this is a pre-splittable slice.
  3214. if (auto *LI = dyn_cast<LoadInst>(I)) {
  3215. assert(!LI->isVolatile() && "Cannot split volatile loads!");
  3216. // The load must be used exclusively to store into other pointers for
  3217. // us to be able to arbitrarily pre-split it. The stores must also be
  3218. // simple to avoid changing semantics.
  3219. auto IsLoadSimplyStored = [](LoadInst *LI) {
  3220. for (User *LU : LI->users()) {
  3221. auto *SI = dyn_cast<StoreInst>(LU);
  3222. if (!SI || !SI->isSimple())
  3223. return false;
  3224. }
  3225. return true;
  3226. };
  3227. if (!IsLoadSimplyStored(LI)) {
  3228. UnsplittableLoads.insert(LI);
  3229. continue;
  3230. }
  3231. Loads.push_back(LI);
  3232. } else if (auto *SI = dyn_cast<StoreInst>(S.getUse()->getUser())) {
  3233. if (!SI ||
  3234. S.getUse() != &SI->getOperandUse(SI->getPointerOperandIndex()))
  3235. continue;
  3236. auto *StoredLoad = dyn_cast<LoadInst>(SI->getValueOperand());
  3237. if (!StoredLoad || !StoredLoad->isSimple())
  3238. continue;
  3239. assert(!SI->isVolatile() && "Cannot split volatile stores!");
  3240. Stores.push_back(SI);
  3241. } else {
  3242. // Other uses cannot be pre-split.
  3243. continue;
  3244. }
  3245. // Record the initial split.
  3246. DEBUG(dbgs() << " Candidate: " << *I << "\n");
  3247. auto &Offsets = SplitOffsetsMap[I];
  3248. assert(Offsets.Splits.empty() &&
  3249. "Should not have splits the first time we see an instruction!");
  3250. Offsets.S = &S;
  3251. Offsets.Splits.push_back(P.endOffset() - S.beginOffset());
  3252. }
  3253. // Now scan the already split slices, and add a split for any of them which
  3254. // we're going to pre-split.
  3255. for (Slice *S : P.splitSliceTails()) {
  3256. auto SplitOffsetsMapI =
  3257. SplitOffsetsMap.find(cast<Instruction>(S->getUse()->getUser()));
  3258. if (SplitOffsetsMapI == SplitOffsetsMap.end())
  3259. continue;
  3260. auto &Offsets = SplitOffsetsMapI->second;
  3261. assert(Offsets.S == S && "Found a mismatched slice!");
  3262. assert(!Offsets.Splits.empty() &&
  3263. "Cannot have an empty set of splits on the second partition!");
  3264. assert(Offsets.Splits.back() ==
  3265. P.beginOffset() - Offsets.S->beginOffset() &&
  3266. "Previous split does not end where this one begins!");
  3267. // Record each split. The last partition's end isn't needed as the size
  3268. // of the slice dictates that.
  3269. if (S->endOffset() > P.endOffset())
  3270. Offsets.Splits.push_back(P.endOffset() - Offsets.S->beginOffset());
  3271. }
  3272. }
  3273. // We may have split loads where some of their stores are split stores. For
  3274. // such loads and stores, we can only pre-split them if their splits exactly
  3275. // match relative to their starting offset. We have to verify this prior to
  3276. // any rewriting.
  3277. Stores.erase(
  3278. std::remove_if(Stores.begin(), Stores.end(),
  3279. [&UnsplittableLoads, &SplitOffsetsMap](StoreInst *SI) {
  3280. // Lookup the load we are storing in our map of split
  3281. // offsets.
  3282. auto *LI = cast<LoadInst>(SI->getValueOperand());
  3283. // If it was completely unsplittable, then we're done,
  3284. // and this store can't be pre-split.
  3285. if (UnsplittableLoads.count(LI))
  3286. return true;
  3287. auto LoadOffsetsI = SplitOffsetsMap.find(LI);
  3288. if (LoadOffsetsI == SplitOffsetsMap.end())
  3289. return false; // Unrelated loads are definitely safe.
  3290. auto &LoadOffsets = LoadOffsetsI->second;
  3291. // Now lookup the store's offsets.
  3292. auto &StoreOffsets = SplitOffsetsMap[SI];
  3293. // If the relative offsets of each split in the load and
  3294. // store match exactly, then we can split them and we
  3295. // don't need to remove them here.
  3296. if (LoadOffsets.Splits == StoreOffsets.Splits)
  3297. return false;
  3298. DEBUG(dbgs()
  3299. << " Mismatched splits for load and store:\n"
  3300. << " " << *LI << "\n"
  3301. << " " << *SI << "\n");
  3302. // We've found a store and load that we need to split
  3303. // with mismatched relative splits. Just give up on them
  3304. // and remove both instructions from our list of
  3305. // candidates.
  3306. UnsplittableLoads.insert(LI);
  3307. return true;
  3308. }),
  3309. Stores.end());
  3310. // Now we have to go *back* through all te stores, because a later store may
  3311. // have caused an earlier store's load to become unsplittable and if it is
  3312. // unsplittable for the later store, then we can't rely on it being split in
  3313. // the earlier store either.
  3314. Stores.erase(std::remove_if(Stores.begin(), Stores.end(),
  3315. [&UnsplittableLoads](StoreInst *SI) {
  3316. auto *LI =
  3317. cast<LoadInst>(SI->getValueOperand());
  3318. return UnsplittableLoads.count(LI);
  3319. }),
  3320. Stores.end());
  3321. // Once we've established all the loads that can't be split for some reason,
  3322. // filter any that made it into our list out.
  3323. Loads.erase(std::remove_if(Loads.begin(), Loads.end(),
  3324. [&UnsplittableLoads](LoadInst *LI) {
  3325. return UnsplittableLoads.count(LI);
  3326. }),
  3327. Loads.end());
  3328. // If no loads or stores are left, there is no pre-splitting to be done for
  3329. // this alloca.
  3330. if (Loads.empty() && Stores.empty())
  3331. return false;
  3332. // From here on, we can't fail and will be building new accesses, so rig up
  3333. // an IR builder.
  3334. IRBuilderTy IRB(&AI);
  3335. // Collect the new slices which we will merge into the alloca slices.
  3336. SmallVector<Slice, 4> NewSlices;
  3337. // Track any allocas we end up splitting loads and stores for so we iterate
  3338. // on them.
  3339. SmallPtrSet<AllocaInst *, 4> ResplitPromotableAllocas;
  3340. // At this point, we have collected all of the loads and stores we can
  3341. // pre-split, and the specific splits needed for them. We actually do the
  3342. // splitting in a specific order in order to handle when one of the loads in
  3343. // the value operand to one of the stores.
  3344. //
  3345. // First, we rewrite all of the split loads, and just accumulate each split
  3346. // load in a parallel structure. We also build the slices for them and append
  3347. // them to the alloca slices.
  3348. SmallDenseMap<LoadInst *, std::vector<LoadInst *>, 1> SplitLoadsMap;
  3349. std::vector<LoadInst *> SplitLoads;
  3350. const DataLayout &DL = AI.getModule()->getDataLayout();
  3351. for (LoadInst *LI : Loads) {
  3352. SplitLoads.clear();
  3353. IntegerType *Ty = cast<IntegerType>(LI->getType());
  3354. uint64_t LoadSize = Ty->getBitWidth() / 8;
  3355. assert(LoadSize > 0 && "Cannot have a zero-sized integer load!");
  3356. auto &Offsets = SplitOffsetsMap[LI];
  3357. assert(LoadSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
  3358. "Slice size should always match load size exactly!");
  3359. uint64_t BaseOffset = Offsets.S->beginOffset();
  3360. assert(BaseOffset + LoadSize > BaseOffset &&
  3361. "Cannot represent alloca access size using 64-bit integers!");
  3362. Instruction *BasePtr = cast<Instruction>(LI->getPointerOperand());
  3363. IRB.SetInsertPoint(BasicBlock::iterator(LI));
  3364. DEBUG(dbgs() << " Splitting load: " << *LI << "\n");
  3365. uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
  3366. int Idx = 0, Size = Offsets.Splits.size();
  3367. for (;;) {
  3368. auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
  3369. auto *PartPtrTy = PartTy->getPointerTo(LI->getPointerAddressSpace());
  3370. LoadInst *PLoad = IRB.CreateAlignedLoad(
  3371. getAdjustedPtr(IRB, DL, BasePtr,
  3372. APInt(DL.getPointerSizeInBits(), PartOffset),
  3373. PartPtrTy, BasePtr->getName() + "."),
  3374. getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
  3375. LI->getName());
  3376. // Append this load onto the list of split loads so we can find it later
  3377. // to rewrite the stores.
  3378. SplitLoads.push_back(PLoad);
  3379. // Now build a new slice for the alloca.
  3380. NewSlices.push_back(
  3381. Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
  3382. &PLoad->getOperandUse(PLoad->getPointerOperandIndex()),
  3383. /*IsSplittable*/ false));
  3384. DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
  3385. << ", " << NewSlices.back().endOffset() << "): " << *PLoad
  3386. << "\n");
  3387. // See if we've handled all the splits.
  3388. if (Idx >= Size)
  3389. break;
  3390. // Setup the next partition.
  3391. PartOffset = Offsets.Splits[Idx];
  3392. ++Idx;
  3393. PartSize = (Idx < Size ? Offsets.Splits[Idx] : LoadSize) - PartOffset;
  3394. }
  3395. // Now that we have the split loads, do the slow walk over all uses of the
  3396. // load and rewrite them as split stores, or save the split loads to use
  3397. // below if the store is going to be split there anyways.
  3398. bool DeferredStores = false;
  3399. for (User *LU : LI->users()) {
  3400. StoreInst *SI = cast<StoreInst>(LU);
  3401. if (!Stores.empty() && SplitOffsetsMap.count(SI)) {
  3402. DeferredStores = true;
  3403. DEBUG(dbgs() << " Deferred splitting of store: " << *SI << "\n");
  3404. continue;
  3405. }
  3406. Value *StoreBasePtr = SI->getPointerOperand();
  3407. IRB.SetInsertPoint(BasicBlock::iterator(SI));
  3408. DEBUG(dbgs() << " Splitting store of load: " << *SI << "\n");
  3409. for (int Idx = 0, Size = SplitLoads.size(); Idx < Size; ++Idx) {
  3410. LoadInst *PLoad = SplitLoads[Idx];
  3411. uint64_t PartOffset = Idx == 0 ? 0 : Offsets.Splits[Idx - 1];
  3412. auto *PartPtrTy =
  3413. PLoad->getType()->getPointerTo(SI->getPointerAddressSpace());
  3414. StoreInst *PStore = IRB.CreateAlignedStore(
  3415. PLoad, getAdjustedPtr(IRB, DL, StoreBasePtr,
  3416. APInt(DL.getPointerSizeInBits(), PartOffset),
  3417. PartPtrTy, StoreBasePtr->getName() + "."),
  3418. getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
  3419. (void)PStore;
  3420. DEBUG(dbgs() << " +" << PartOffset << ":" << *PStore << "\n");
  3421. }
  3422. // We want to immediately iterate on any allocas impacted by splitting
  3423. // this store, and we have to track any promotable alloca (indicated by
  3424. // a direct store) as needing to be resplit because it is no longer
  3425. // promotable.
  3426. if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(StoreBasePtr)) {
  3427. ResplitPromotableAllocas.insert(OtherAI);
  3428. Worklist.insert(OtherAI);
  3429. } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
  3430. StoreBasePtr->stripInBoundsOffsets())) {
  3431. Worklist.insert(OtherAI);
  3432. }
  3433. // Mark the original store as dead.
  3434. DeadInsts.insert(SI);
  3435. }
  3436. // Save the split loads if there are deferred stores among the users.
  3437. if (DeferredStores)
  3438. SplitLoadsMap.insert(std::make_pair(LI, std::move(SplitLoads)));
  3439. // Mark the original load as dead and kill the original slice.
  3440. DeadInsts.insert(LI);
  3441. Offsets.S->kill();
  3442. }
  3443. // Second, we rewrite all of the split stores. At this point, we know that
  3444. // all loads from this alloca have been split already. For stores of such
  3445. // loads, we can simply look up the pre-existing split loads. For stores of
  3446. // other loads, we split those loads first and then write split stores of
  3447. // them.
  3448. for (StoreInst *SI : Stores) {
  3449. auto *LI = cast<LoadInst>(SI->getValueOperand());
  3450. IntegerType *Ty = cast<IntegerType>(LI->getType());
  3451. uint64_t StoreSize = Ty->getBitWidth() / 8;
  3452. assert(StoreSize > 0 && "Cannot have a zero-sized integer store!");
  3453. auto &Offsets = SplitOffsetsMap[SI];
  3454. assert(StoreSize == Offsets.S->endOffset() - Offsets.S->beginOffset() &&
  3455. "Slice size should always match load size exactly!");
  3456. uint64_t BaseOffset = Offsets.S->beginOffset();
  3457. assert(BaseOffset + StoreSize > BaseOffset &&
  3458. "Cannot represent alloca access size using 64-bit integers!");
  3459. Value *LoadBasePtr = LI->getPointerOperand();
  3460. Instruction *StoreBasePtr = cast<Instruction>(SI->getPointerOperand());
  3461. DEBUG(dbgs() << " Splitting store: " << *SI << "\n");
  3462. // Check whether we have an already split load.
  3463. auto SplitLoadsMapI = SplitLoadsMap.find(LI);
  3464. std::vector<LoadInst *> *SplitLoads = nullptr;
  3465. if (SplitLoadsMapI != SplitLoadsMap.end()) {
  3466. SplitLoads = &SplitLoadsMapI->second;
  3467. assert(SplitLoads->size() == Offsets.Splits.size() + 1 &&
  3468. "Too few split loads for the number of splits in the store!");
  3469. } else {
  3470. DEBUG(dbgs() << " of load: " << *LI << "\n");
  3471. }
  3472. uint64_t PartOffset = 0, PartSize = Offsets.Splits.front();
  3473. int Idx = 0, Size = Offsets.Splits.size();
  3474. for (;;) {
  3475. auto *PartTy = Type::getIntNTy(Ty->getContext(), PartSize * 8);
  3476. auto *PartPtrTy = PartTy->getPointerTo(SI->getPointerAddressSpace());
  3477. // Either lookup a split load or create one.
  3478. LoadInst *PLoad;
  3479. if (SplitLoads) {
  3480. PLoad = (*SplitLoads)[Idx];
  3481. } else {
  3482. IRB.SetInsertPoint(BasicBlock::iterator(LI));
  3483. PLoad = IRB.CreateAlignedLoad(
  3484. getAdjustedPtr(IRB, DL, LoadBasePtr,
  3485. APInt(DL.getPointerSizeInBits(), PartOffset),
  3486. PartPtrTy, LoadBasePtr->getName() + "."),
  3487. getAdjustedAlignment(LI, PartOffset, DL), /*IsVolatile*/ false,
  3488. LI->getName());
  3489. }
  3490. // And store this partition.
  3491. IRB.SetInsertPoint(BasicBlock::iterator(SI));
  3492. StoreInst *PStore = IRB.CreateAlignedStore(
  3493. PLoad, getAdjustedPtr(IRB, DL, StoreBasePtr,
  3494. APInt(DL.getPointerSizeInBits(), PartOffset),
  3495. PartPtrTy, StoreBasePtr->getName() + "."),
  3496. getAdjustedAlignment(SI, PartOffset, DL), /*IsVolatile*/ false);
  3497. // Now build a new slice for the alloca.
  3498. NewSlices.push_back(
  3499. Slice(BaseOffset + PartOffset, BaseOffset + PartOffset + PartSize,
  3500. &PStore->getOperandUse(PStore->getPointerOperandIndex()),
  3501. /*IsSplittable*/ false));
  3502. DEBUG(dbgs() << " new slice [" << NewSlices.back().beginOffset()
  3503. << ", " << NewSlices.back().endOffset() << "): " << *PStore
  3504. << "\n");
  3505. if (!SplitLoads) {
  3506. DEBUG(dbgs() << " of split load: " << *PLoad << "\n");
  3507. }
  3508. // See if we've finished all the splits.
  3509. if (Idx >= Size)
  3510. break;
  3511. // Setup the next partition.
  3512. PartOffset = Offsets.Splits[Idx];
  3513. ++Idx;
  3514. PartSize = (Idx < Size ? Offsets.Splits[Idx] : StoreSize) - PartOffset;
  3515. }
  3516. // We want to immediately iterate on any allocas impacted by splitting
  3517. // this load, which is only relevant if it isn't a load of this alloca and
  3518. // thus we didn't already split the loads above. We also have to keep track
  3519. // of any promotable allocas we split loads on as they can no longer be
  3520. // promoted.
  3521. if (!SplitLoads) {
  3522. if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(LoadBasePtr)) {
  3523. assert(OtherAI != &AI && "We can't re-split our own alloca!");
  3524. ResplitPromotableAllocas.insert(OtherAI);
  3525. Worklist.insert(OtherAI);
  3526. } else if (AllocaInst *OtherAI = dyn_cast<AllocaInst>(
  3527. LoadBasePtr->stripInBoundsOffsets())) {
  3528. assert(OtherAI != &AI && "We can't re-split our own alloca!");
  3529. Worklist.insert(OtherAI);
  3530. }
  3531. }
  3532. // Mark the original store as dead now that we've split it up and kill its
  3533. // slice. Note that we leave the original load in place unless this store
  3534. // was its ownly use. It may in turn be split up if it is an alloca load
  3535. // for some other alloca, but it may be a normal load. This may introduce
  3536. // redundant loads, but where those can be merged the rest of the optimizer
  3537. // should handle the merging, and this uncovers SSA splits which is more
  3538. // important. In practice, the original loads will almost always be fully
  3539. // split and removed eventually, and the splits will be merged by any
  3540. // trivial CSE, including instcombine.
  3541. if (LI->hasOneUse()) {
  3542. assert(*LI->user_begin() == SI && "Single use isn't this store!");
  3543. DeadInsts.insert(LI);
  3544. }
  3545. DeadInsts.insert(SI);
  3546. Offsets.S->kill();
  3547. }
  3548. // Remove the killed slices that have ben pre-split.
  3549. AS.erase(std::remove_if(AS.begin(), AS.end(), [](const Slice &S) {
  3550. return S.isDead();
  3551. }), AS.end());
  3552. // Insert our new slices. This will sort and merge them into the sorted
  3553. // sequence.
  3554. AS.insert(NewSlices);
  3555. DEBUG(dbgs() << " Pre-split slices:\n");
  3556. #ifndef NDEBUG
  3557. for (auto I = AS.begin(), E = AS.end(); I != E; ++I)
  3558. DEBUG(AS.print(dbgs(), I, " "));
  3559. #endif
  3560. // Finally, don't try to promote any allocas that new require re-splitting.
  3561. // They have already been added to the worklist above.
  3562. PromotableAllocas.erase(
  3563. std::remove_if(
  3564. PromotableAllocas.begin(), PromotableAllocas.end(),
  3565. [&](AllocaInst *AI) { return ResplitPromotableAllocas.count(AI); }),
  3566. PromotableAllocas.end());
  3567. return true;
  3568. }
  3569. /// \brief Rewrite an alloca partition's users.
  3570. ///
  3571. /// This routine drives both of the rewriting goals of the SROA pass. It tries
  3572. /// to rewrite uses of an alloca partition to be conducive for SSA value
  3573. /// promotion. If the partition needs a new, more refined alloca, this will
  3574. /// build that new alloca, preserving as much type information as possible, and
  3575. /// rewrite the uses of the old alloca to point at the new one and have the
  3576. /// appropriate new offsets. It also evaluates how successful the rewrite was
  3577. /// at enabling promotion and if it was successful queues the alloca to be
  3578. /// promoted.
  3579. AllocaInst *SROA::rewritePartition(AllocaInst &AI, AllocaSlices &AS,
  3580. AllocaSlices::Partition &P) {
  3581. // Try to compute a friendly type for this partition of the alloca. This
  3582. // won't always succeed, in which case we fall back to a legal integer type
  3583. // or an i8 array of an appropriate size.
  3584. Type *SliceTy = nullptr;
  3585. const DataLayout &DL = AI.getModule()->getDataLayout();
  3586. if (Type *CommonUseTy = findCommonType(P.begin(), P.end(), P.endOffset()))
  3587. if (DL.getTypeAllocSize(CommonUseTy) >= P.size())
  3588. SliceTy = CommonUseTy;
  3589. if (!SliceTy)
  3590. if (Type *TypePartitionTy = getTypePartition(DL, AI.getAllocatedType(),
  3591. P.beginOffset(), P.size()))
  3592. SliceTy = TypePartitionTy;
  3593. if ((!SliceTy || (SliceTy->isArrayTy() &&
  3594. SliceTy->getArrayElementType()->isIntegerTy())) &&
  3595. DL.isLegalInteger(P.size() * 8))
  3596. SliceTy = Type::getIntNTy(*C, P.size() * 8);
  3597. if (!SliceTy)
  3598. SliceTy = ArrayType::get(Type::getInt8Ty(*C), P.size());
  3599. assert(DL.getTypeAllocSize(SliceTy) >= P.size());
  3600. bool IsIntegerPromotable = isIntegerWideningViable(P, SliceTy, DL);
  3601. VectorType *VecTy =
  3602. IsIntegerPromotable ? nullptr : isVectorPromotionViable(P, DL);
  3603. if (VecTy)
  3604. SliceTy = VecTy;
  3605. // Check for the case where we're going to rewrite to a new alloca of the
  3606. // exact same type as the original, and with the same access offsets. In that
  3607. // case, re-use the existing alloca, but still run through the rewriter to
  3608. // perform phi and select speculation.
  3609. AllocaInst *NewAI;
  3610. if (SliceTy == AI.getAllocatedType()) {
  3611. assert(P.beginOffset() == 0 &&
  3612. "Non-zero begin offset but same alloca type");
  3613. NewAI = &AI;
  3614. // FIXME: We should be able to bail at this point with "nothing changed".
  3615. // FIXME: We might want to defer PHI speculation until after here.
  3616. // FIXME: return nullptr;
  3617. } else {
  3618. unsigned Alignment = AI.getAlignment();
  3619. if (!Alignment) {
  3620. // The minimum alignment which users can rely on when the explicit
  3621. // alignment is omitted or zero is that required by the ABI for this
  3622. // type.
  3623. Alignment = DL.getABITypeAlignment(AI.getAllocatedType());
  3624. }
  3625. Alignment = MinAlign(Alignment, P.beginOffset());
  3626. // If we will get at least this much alignment from the type alone, leave
  3627. // the alloca's alignment unconstrained.
  3628. if (Alignment <= DL.getABITypeAlignment(SliceTy))
  3629. Alignment = 0;
  3630. NewAI = new AllocaInst(
  3631. SliceTy, nullptr, Alignment,
  3632. AI.getName() + ".sroa." + Twine(P.begin() - AS.begin()), &AI);
  3633. ++NumNewAllocas;
  3634. }
  3635. DEBUG(dbgs() << "Rewriting alloca partition "
  3636. << "[" << P.beginOffset() << "," << P.endOffset()
  3637. << ") to: " << *NewAI << "\n");
  3638. // Track the high watermark on the worklist as it is only relevant for
  3639. // promoted allocas. We will reset it to this point if the alloca is not in
  3640. // fact scheduled for promotion.
  3641. unsigned PPWOldSize = PostPromotionWorklist.size();
  3642. unsigned NumUses = 0;
  3643. SmallPtrSet<PHINode *, 8> PHIUsers;
  3644. SmallPtrSet<SelectInst *, 8> SelectUsers;
  3645. AllocaSliceRewriter Rewriter(DL, AS, *this, AI, *NewAI, P.beginOffset(),
  3646. P.endOffset(), IsIntegerPromotable, VecTy,
  3647. PHIUsers, SelectUsers);
  3648. bool Promotable = true;
  3649. for (Slice *S : P.splitSliceTails()) {
  3650. Promotable &= Rewriter.visit(S);
  3651. ++NumUses;
  3652. }
  3653. for (Slice &S : P) {
  3654. Promotable &= Rewriter.visit(&S);
  3655. ++NumUses;
  3656. }
  3657. NumAllocaPartitionUses += NumUses;
  3658. MaxUsesPerAllocaPartition =
  3659. std::max<unsigned>(NumUses, MaxUsesPerAllocaPartition);
  3660. // Now that we've processed all the slices in the new partition, check if any
  3661. // PHIs or Selects would block promotion.
  3662. for (SmallPtrSetImpl<PHINode *>::iterator I = PHIUsers.begin(),
  3663. E = PHIUsers.end();
  3664. I != E; ++I)
  3665. if (!isSafePHIToSpeculate(**I)) {
  3666. Promotable = false;
  3667. PHIUsers.clear();
  3668. SelectUsers.clear();
  3669. break;
  3670. }
  3671. for (SmallPtrSetImpl<SelectInst *>::iterator I = SelectUsers.begin(),
  3672. E = SelectUsers.end();
  3673. I != E; ++I)
  3674. if (!isSafeSelectToSpeculate(**I)) {
  3675. Promotable = false;
  3676. PHIUsers.clear();
  3677. SelectUsers.clear();
  3678. break;
  3679. }
  3680. if (Promotable) {
  3681. if (PHIUsers.empty() && SelectUsers.empty()) {
  3682. // Promote the alloca.
  3683. PromotableAllocas.push_back(NewAI);
  3684. } else {
  3685. // If we have either PHIs or Selects to speculate, add them to those
  3686. // worklists and re-queue the new alloca so that we promote in on the
  3687. // next iteration.
  3688. for (PHINode *PHIUser : PHIUsers)
  3689. SpeculatablePHIs.insert(PHIUser);
  3690. for (SelectInst *SelectUser : SelectUsers)
  3691. SpeculatableSelects.insert(SelectUser);
  3692. Worklist.insert(NewAI);
  3693. }
  3694. } else {
  3695. // If we can't promote the alloca, iterate on it to check for new
  3696. // refinements exposed by splitting the current alloca. Don't iterate on an
  3697. // alloca which didn't actually change and didn't get promoted.
  3698. if (NewAI != &AI)
  3699. Worklist.insert(NewAI);
  3700. // Drop any post-promotion work items if promotion didn't happen.
  3701. while (PostPromotionWorklist.size() > PPWOldSize)
  3702. PostPromotionWorklist.pop_back();
  3703. }
  3704. return NewAI;
  3705. }
  3706. /// \brief Walks the slices of an alloca and form partitions based on them,
  3707. /// rewriting each of their uses.
  3708. bool SROA::splitAlloca(AllocaInst &AI, AllocaSlices &AS) {
  3709. if (AS.begin() == AS.end())
  3710. return false;
  3711. unsigned NumPartitions = 0;
  3712. bool Changed = false;
  3713. const DataLayout &DL = AI.getModule()->getDataLayout();
  3714. // First try to pre-split loads and stores.
  3715. Changed |= presplitLoadsAndStores(AI, AS);
  3716. // Now that we have identified any pre-splitting opportunities, mark any
  3717. // splittable (non-whole-alloca) loads and stores as unsplittable. If we fail
  3718. // to split these during pre-splitting, we want to force them to be
  3719. // rewritten into a partition.
  3720. bool IsSorted = true;
  3721. for (Slice &S : AS) {
  3722. if (!S.isSplittable())
  3723. continue;
  3724. // FIXME: We currently leave whole-alloca splittable loads and stores. This
  3725. // used to be the only splittable loads and stores and we need to be
  3726. // confident that the above handling of splittable loads and stores is
  3727. // completely sufficient before we forcibly disable the remaining handling.
  3728. if (S.beginOffset() == 0 &&
  3729. S.endOffset() >= DL.getTypeAllocSize(AI.getAllocatedType()))
  3730. continue;
  3731. if (isa<LoadInst>(S.getUse()->getUser()) ||
  3732. isa<StoreInst>(S.getUse()->getUser())) {
  3733. S.makeUnsplittable();
  3734. IsSorted = false;
  3735. }
  3736. }
  3737. if (!IsSorted)
  3738. std::sort(AS.begin(), AS.end());
  3739. /// \brief Describes the allocas introduced by rewritePartition
  3740. /// in order to migrate the debug info.
  3741. struct Piece {
  3742. AllocaInst *Alloca;
  3743. uint64_t Offset;
  3744. uint64_t Size;
  3745. Piece(AllocaInst *AI, uint64_t O, uint64_t S)
  3746. : Alloca(AI), Offset(O), Size(S) {}
  3747. };
  3748. SmallVector<Piece, 4> Pieces;
  3749. // Rewrite each partition.
  3750. for (auto &P : AS.partitions()) {
  3751. if (AllocaInst *NewAI = rewritePartition(AI, AS, P)) {
  3752. Changed = true;
  3753. if (NewAI != &AI) {
  3754. uint64_t SizeOfByte = 8;
  3755. uint64_t AllocaSize = DL.getTypeSizeInBits(NewAI->getAllocatedType());
  3756. // Don't include any padding.
  3757. uint64_t Size = std::min(AllocaSize, P.size() * SizeOfByte);
  3758. Pieces.push_back(Piece(NewAI, P.beginOffset() * SizeOfByte, Size));
  3759. }
  3760. }
  3761. ++NumPartitions;
  3762. }
  3763. NumAllocaPartitions += NumPartitions;
  3764. MaxPartitionsPerAlloca =
  3765. std::max<unsigned>(NumPartitions, MaxPartitionsPerAlloca);
  3766. // Migrate debug information from the old alloca to the new alloca(s)
  3767. // and the individial partitions.
  3768. if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(&AI)) {
  3769. auto *Var = DbgDecl->getVariable();
  3770. auto *Expr = DbgDecl->getExpression();
  3771. DIBuilder DIB(*AI.getParent()->getParent()->getParent(),
  3772. /*AllowUnresolved*/ false);
  3773. bool IsSplit = Pieces.size() > 1;
  3774. for (auto Piece : Pieces) {
  3775. // Create a piece expression describing the new partition or reuse AI's
  3776. // expression if there is only one partition.
  3777. auto *PieceExpr = Expr;
  3778. if (IsSplit || Expr->isBitPiece()) {
  3779. // If this alloca is already a scalar replacement of a larger aggregate,
  3780. // Piece.Offset describes the offset inside the scalar.
  3781. uint64_t Offset = Expr->isBitPiece() ? Expr->getBitPieceOffset() : 0;
  3782. uint64_t Start = Offset + Piece.Offset;
  3783. uint64_t Size = Piece.Size;
  3784. if (Expr->isBitPiece()) {
  3785. uint64_t AbsEnd = Expr->getBitPieceOffset() + Expr->getBitPieceSize();
  3786. if (Start >= AbsEnd)
  3787. // No need to describe a SROAed padding.
  3788. continue;
  3789. Size = std::min(Size, AbsEnd - Start);
  3790. }
  3791. PieceExpr = DIB.createBitPieceExpression(Start, Size);
  3792. }
  3793. // Remove any existing dbg.declare intrinsic describing the same alloca.
  3794. if (DbgDeclareInst *OldDDI = FindAllocaDbgDeclare(Piece.Alloca))
  3795. OldDDI->eraseFromParent();
  3796. DIB.insertDeclare(Piece.Alloca, Var, PieceExpr, DbgDecl->getDebugLoc(),
  3797. &AI);
  3798. }
  3799. }
  3800. return Changed;
  3801. }
  3802. /// \brief Clobber a use with undef, deleting the used value if it becomes dead.
  3803. void SROA::clobberUse(Use &U) {
  3804. Value *OldV = U;
  3805. // Replace the use with an undef value.
  3806. U = UndefValue::get(OldV->getType());
  3807. // Check for this making an instruction dead. We have to garbage collect
  3808. // all the dead instructions to ensure the uses of any alloca end up being
  3809. // minimal.
  3810. if (Instruction *OldI = dyn_cast<Instruction>(OldV))
  3811. if (isInstructionTriviallyDead(OldI)) {
  3812. DeadInsts.insert(OldI);
  3813. }
  3814. }
  3815. /// \brief Analyze an alloca for SROA.
  3816. ///
  3817. /// This analyzes the alloca to ensure we can reason about it, builds
  3818. /// the slices of the alloca, and then hands it off to be split and
  3819. /// rewritten as needed.
  3820. bool SROA::runOnAlloca(AllocaInst &AI) {
  3821. DEBUG(dbgs() << "SROA alloca: " << AI << "\n");
  3822. ++NumAllocasAnalyzed;
  3823. // Special case dead allocas, as they're trivial.
  3824. if (AI.use_empty()) {
  3825. AI.eraseFromParent();
  3826. return true;
  3827. }
  3828. const DataLayout &DL = AI.getModule()->getDataLayout();
  3829. // Skip alloca forms that this analysis can't handle.
  3830. if (AI.isArrayAllocation() || !AI.getAllocatedType()->isSized() ||
  3831. hlsl::dxilutil::IsHLSLObjectType(
  3832. AI.getAllocatedType()) || // HLSL Change - not sroa resource type.
  3833. // HLSL Change Begin - not sroa matrix type.
  3834. (SkipHLSLMat &&
  3835. hlsl::dxilutil::IsHLSLMatrixType(AI.getAllocatedType())) ||
  3836. // HLSL Change End.
  3837. DL.getTypeAllocSize(AI.getAllocatedType()) == 0)
  3838. return false;
  3839. bool Changed = false;
  3840. // First, split any FCA loads and stores touching this alloca to promote
  3841. // better splitting and promotion opportunities.
  3842. AggLoadStoreRewriter AggRewriter(DL, SkipHLSLMat);
  3843. Changed |= AggRewriter.rewrite(AI);
  3844. // Build the slices using a recursive instruction-visiting builder.
  3845. AllocaSlices AS(DL, AI, SkipHLSLMat);
  3846. DEBUG(AS.print(dbgs()));
  3847. if (AS.isEscaped())
  3848. return Changed;
  3849. // Delete all the dead users of this alloca before splitting and rewriting it.
  3850. for (Instruction *DeadUser : AS.getDeadUsers()) {
  3851. // Free up everything used by this instruction.
  3852. for (Use &DeadOp : DeadUser->operands())
  3853. clobberUse(DeadOp);
  3854. // Now replace the uses of this instruction.
  3855. DeadUser->replaceAllUsesWith(UndefValue::get(DeadUser->getType()));
  3856. // And mark it for deletion.
  3857. DeadInsts.insert(DeadUser);
  3858. Changed = true;
  3859. }
  3860. for (Use *DeadOp : AS.getDeadOperands()) {
  3861. clobberUse(*DeadOp);
  3862. Changed = true;
  3863. }
  3864. // No slices to split. Leave the dead alloca for a later pass to clean up.
  3865. if (AS.begin() == AS.end())
  3866. return Changed;
  3867. Changed |= splitAlloca(AI, AS);
  3868. DEBUG(dbgs() << " Speculating PHIs\n");
  3869. while (!SpeculatablePHIs.empty())
  3870. speculatePHINodeLoads(*SpeculatablePHIs.pop_back_val());
  3871. DEBUG(dbgs() << " Speculating Selects\n");
  3872. while (!SpeculatableSelects.empty())
  3873. speculateSelectInstLoads(*SpeculatableSelects.pop_back_val());
  3874. return Changed;
  3875. }
  3876. /// \brief Delete the dead instructions accumulated in this run.
  3877. ///
  3878. /// Recursively deletes the dead instructions we've accumulated. This is done
  3879. /// at the very end to maximize locality of the recursive delete and to
  3880. /// minimize the problems of invalidated instruction pointers as such pointers
  3881. /// are used heavily in the intermediate stages of the algorithm.
  3882. ///
  3883. /// We also record the alloca instructions deleted here so that they aren't
  3884. /// subsequently handed to mem2reg to promote.
  3885. void SROA::deleteDeadInstructions(
  3886. SmallPtrSetImpl<AllocaInst *> &DeletedAllocas) {
  3887. while (!DeadInsts.empty()) {
  3888. Instruction *I = DeadInsts.pop_back_val();
  3889. DEBUG(dbgs() << "Deleting dead instruction: " << *I << "\n");
  3890. I->replaceAllUsesWith(UndefValue::get(I->getType()));
  3891. for (Use &Operand : I->operands())
  3892. if (Instruction *U = dyn_cast<Instruction>(Operand)) {
  3893. // Zero out the operand and see if it becomes trivially dead.
  3894. Operand = nullptr;
  3895. if (isInstructionTriviallyDead(U))
  3896. DeadInsts.insert(U);
  3897. }
  3898. if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
  3899. DeletedAllocas.insert(AI);
  3900. if (DbgDeclareInst *DbgDecl = FindAllocaDbgDeclare(AI))
  3901. DbgDecl->eraseFromParent();
  3902. }
  3903. ++NumDeleted;
  3904. I->eraseFromParent();
  3905. }
  3906. }
  3907. static void enqueueUsersInWorklist(Instruction &I,
  3908. SmallVectorImpl<Instruction *> &Worklist,
  3909. SmallPtrSetImpl<Instruction *> &Visited) {
  3910. for (User *U : I.users())
  3911. if (Visited.insert(cast<Instruction>(U)).second)
  3912. Worklist.push_back(cast<Instruction>(U));
  3913. }
  3914. /// \brief Promote the allocas, using the best available technique.
  3915. ///
  3916. /// This attempts to promote whatever allocas have been identified as viable in
  3917. /// the PromotableAllocas list. If that list is empty, there is nothing to do.
  3918. /// If there is a domtree available, we attempt to promote using the full power
  3919. /// of mem2reg. Otherwise, we build and use the AllocaPromoter above which is
  3920. /// based on the SSAUpdater utilities. This function returns whether any
  3921. /// promotion occurred.
  3922. bool SROA::promoteAllocas(Function &F) {
  3923. if (PromotableAllocas.empty())
  3924. return false;
  3925. NumPromoted += PromotableAllocas.size();
  3926. if (DT && !ForceSSAUpdater) {
  3927. DEBUG(dbgs() << "Promoting allocas with mem2reg...\n");
  3928. PromoteMemToReg(PromotableAllocas, *DT, nullptr, AC);
  3929. PromotableAllocas.clear();
  3930. return true;
  3931. }
  3932. DEBUG(dbgs() << "Promoting allocas with SSAUpdater...\n");
  3933. SSAUpdater SSA;
  3934. DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
  3935. SmallVector<Instruction *, 64> Insts;
  3936. // We need a worklist to walk the uses of each alloca.
  3937. SmallVector<Instruction *, 8> Worklist;
  3938. SmallPtrSet<Instruction *, 8> Visited;
  3939. SmallVector<Instruction *, 32> DeadInsts;
  3940. for (unsigned Idx = 0, Size = PromotableAllocas.size(); Idx != Size; ++Idx) {
  3941. AllocaInst *AI = PromotableAllocas[Idx];
  3942. Insts.clear();
  3943. Worklist.clear();
  3944. Visited.clear();
  3945. enqueueUsersInWorklist(*AI, Worklist, Visited);
  3946. while (!Worklist.empty()) {
  3947. Instruction *I = Worklist.pop_back_val();
  3948. // FIXME: Currently the SSAUpdater infrastructure doesn't reason about
  3949. // lifetime intrinsics and so we strip them (and the bitcasts+GEPs
  3950. // leading to them) here. Eventually it should use them to optimize the
  3951. // scalar values produced.
  3952. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  3953. assert(II->getIntrinsicID() == Intrinsic::lifetime_start ||
  3954. II->getIntrinsicID() == Intrinsic::lifetime_end);
  3955. II->eraseFromParent();
  3956. continue;
  3957. }
  3958. // Push the loads and stores we find onto the list. SROA will already
  3959. // have validated that all loads and stores are viable candidates for
  3960. // promotion.
  3961. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  3962. assert(LI->getType() == AI->getAllocatedType());
  3963. Insts.push_back(LI);
  3964. continue;
  3965. }
  3966. if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  3967. assert(SI->getValueOperand()->getType() == AI->getAllocatedType());
  3968. Insts.push_back(SI);
  3969. continue;
  3970. }
  3971. // For everything else, we know that only no-op bitcasts and GEPs will
  3972. // make it this far, just recurse through them and recall them for later
  3973. // removal.
  3974. DeadInsts.push_back(I);
  3975. enqueueUsersInWorklist(*I, Worklist, Visited);
  3976. }
  3977. AllocaPromoter(Insts, SSA, *AI, DIB).run(Insts);
  3978. while (!DeadInsts.empty())
  3979. DeadInsts.pop_back_val()->eraseFromParent();
  3980. AI->eraseFromParent();
  3981. }
  3982. PromotableAllocas.clear();
  3983. return true;
  3984. }
  3985. bool SROA::runOnFunction(Function &F) {
  3986. if (skipOptnoneFunction(F))
  3987. return false;
  3988. DEBUG(dbgs() << "SROA function: " << F.getName() << "\n");
  3989. C = &F.getContext();
  3990. DominatorTreeWrapperPass *DTWP =
  3991. getAnalysisIfAvailable<DominatorTreeWrapperPass>();
  3992. DT = DTWP ? &DTWP->getDomTree() : nullptr;
  3993. AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  3994. BasicBlock &EntryBB = F.getEntryBlock();
  3995. for (BasicBlock::iterator I = EntryBB.begin(), E = std::prev(EntryBB.end());
  3996. I != E; ++I) {
  3997. if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
  3998. Worklist.insert(AI);
  3999. }
  4000. bool Changed = false;
  4001. // A set of deleted alloca instruction pointers which should be removed from
  4002. // the list of promotable allocas.
  4003. SmallPtrSet<AllocaInst *, 4> DeletedAllocas;
  4004. do {
  4005. while (!Worklist.empty()) {
  4006. Changed |= runOnAlloca(*Worklist.pop_back_val());
  4007. deleteDeadInstructions(DeletedAllocas);
  4008. // Remove the deleted allocas from various lists so that we don't try to
  4009. // continue processing them.
  4010. if (!DeletedAllocas.empty()) {
  4011. auto IsInSet = [&](AllocaInst *AI) { return DeletedAllocas.count(AI); };
  4012. Worklist.remove_if(IsInSet);
  4013. PostPromotionWorklist.remove_if(IsInSet);
  4014. PromotableAllocas.erase(std::remove_if(PromotableAllocas.begin(),
  4015. PromotableAllocas.end(),
  4016. IsInSet),
  4017. PromotableAllocas.end());
  4018. DeletedAllocas.clear();
  4019. }
  4020. }
  4021. Changed |= promoteAllocas(F);
  4022. Worklist = PostPromotionWorklist;
  4023. PostPromotionWorklist.clear();
  4024. } while (!Worklist.empty());
  4025. return Changed;
  4026. }
  4027. void SROA::getAnalysisUsage(AnalysisUsage &AU) const {
  4028. AU.addRequired<AssumptionCacheTracker>();
  4029. if (RequiresDomTree)
  4030. AU.addRequired<DominatorTreeWrapperPass>();
  4031. AU.setPreservesCFG();
  4032. }