SROA.cpp 176 KB

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